idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
54,600 | def _moments_central ( data , center = None , order = 1 ) : data = np . asarray ( data ) . astype ( float ) if data . ndim != 2 : raise ValueError ( 'data must be a 2D array.' ) if center is None : from . . centroids import centroid_com center = centroid_com ( data ) indices = np . ogrid [ [ slice ( 0 , i ) for i in da... | Calculate the central image moments up to the specified order . |
54,601 | def first_and_second_harmonic_function ( phi , c ) : return ( c [ 0 ] + c [ 1 ] * np . sin ( phi ) + c [ 2 ] * np . cos ( phi ) + c [ 3 ] * np . sin ( 2 * phi ) + c [ 4 ] * np . cos ( 2 * phi ) ) | Compute the harmonic function value used to calculate the corrections for ellipse fitting . |
54,602 | def _radial_distance ( shape ) : if len ( shape ) != 2 : raise ValueError ( 'shape must have only 2 elements' ) position = ( np . asarray ( shape ) - 1 ) / 2. x = np . arange ( shape [ 1 ] ) - position [ 1 ] y = np . arange ( shape [ 0 ] ) - position [ 0 ] xx , yy = np . meshgrid ( x , y ) return np . sqrt ( xx ** 2 + ... | Return an array where each value is the Euclidean distance from the array center . |
54,603 | def load_spitzer_image ( show_progress = False ) : path = get_path ( 'spitzer_example_image.fits' , location = 'remote' , show_progress = show_progress ) hdu = fits . open ( path ) [ 0 ] return hdu | Load a 4 . 5 micron Spitzer image . |
54,604 | def load_spitzer_catalog ( show_progress = False ) : path = get_path ( 'spitzer_example_catalog.xml' , location = 'remote' , show_progress = show_progress ) table = Table . read ( path ) return table | Load a 4 . 5 micron Spitzer catalog . |
54,605 | def load_irac_psf ( channel , show_progress = False ) : channel = int ( channel ) if channel < 1 or channel > 4 : raise ValueError ( 'channel must be 1, 2, 3, or 4' ) fn = 'irac_ch{0}_flight.fits' . format ( channel ) path = get_path ( fn , location = 'remote' , show_progress = show_progress ) hdu = fits . open ( path ... | Load a Spitzer IRAC PSF image . |
54,606 | def fit_image ( self , sma0 = None , minsma = 0. , maxsma = None , step = 0.1 , conver = DEFAULT_CONVERGENCE , minit = DEFAULT_MINIT , maxit = DEFAULT_MAXIT , fflag = DEFAULT_FFLAG , maxgerr = DEFAULT_MAXGERR , sclip = 3. , nclip = 0 , integrmode = BILINEAR , linear = False , maxrit = None ) : isophote_list = [ ] if no... | Fit multiple isophotes to the image array . |
54,607 | def fit_isophote ( self , sma , step = 0.1 , conver = DEFAULT_CONVERGENCE , minit = DEFAULT_MINIT , maxit = DEFAULT_MAXIT , fflag = DEFAULT_FFLAG , maxgerr = DEFAULT_MAXGERR , sclip = 3. , nclip = 0 , integrmode = BILINEAR , linear = False , maxrit = None , noniterate = False , going_inwards = False , isophote_list = N... | Fit a single isophote with a given semimajor axis length . |
54,608 | def to_sky ( self , wcs , mode = 'all' ) : sky_params = self . _to_sky_params ( wcs , mode = mode ) return SkyCircularAperture ( ** sky_params ) | Convert the aperture to a SkyCircularAperture object defined in celestial coordinates . |
54,609 | def to_sky ( self , wcs , mode = 'all' ) : sky_params = self . _to_sky_params ( wcs , mode = mode ) return SkyCircularAnnulus ( ** sky_params ) | Convert the aperture to a SkyCircularAnnulus object defined in celestial coordinates . |
54,610 | def to_pixel ( self , wcs , mode = 'all' ) : pixel_params = self . _to_pixel_params ( wcs , mode = mode ) return CircularAperture ( ** pixel_params ) | Convert the aperture to a CircularAperture object defined in pixel coordinates . |
54,611 | def to_pixel ( self , wcs , mode = 'all' ) : pixel_params = self . _to_pixel_params ( wcs , mode = mode ) return CircularAnnulus ( ** pixel_params ) | Convert the aperture to a CircularAnnulus object defined in pixel coordinates . |
54,612 | def apply_poisson_noise ( data , random_state = None ) : data = np . asanyarray ( data ) if np . any ( data < 0 ) : raise ValueError ( 'data must not contain any negative values' ) prng = check_random_state ( random_state ) return prng . poisson ( data ) | Apply Poisson noise to an array where the value of each element in the input array represents the expected number of counts . |
54,613 | def make_noise_image ( shape , type = 'gaussian' , mean = None , stddev = None , random_state = None ) : if mean is None : raise ValueError ( '"mean" must be input' ) prng = check_random_state ( random_state ) if type == 'gaussian' : if stddev is None : raise ValueError ( '"stddev" must be input for Gaussian noise' ) i... | Make a noise image containing Gaussian or Poisson noise . |
54,614 | def make_random_models_table ( n_sources , param_ranges , random_state = None ) : prng = check_random_state ( random_state ) sources = Table ( ) for param_name , ( lower , upper ) in param_ranges . items ( ) : sources [ param_name ] = prng . uniform ( lower , upper , n_sources ) return sources | Make a ~astropy . table . Table containing randomly generated parameters for an Astropy model to simulate a set of sources . |
54,615 | def make_random_gaussians_table ( n_sources , param_ranges , random_state = None ) : sources = make_random_models_table ( n_sources , param_ranges , random_state = random_state ) if 'flux' in param_ranges and 'amplitude' not in param_ranges : model = Gaussian2D ( x_stddev = 1 , y_stddev = 1 ) if 'x_stddev' in sources .... | Make a ~astropy . table . Table containing randomly generated parameters for 2D Gaussian sources . |
54,616 | def make_model_sources_image ( shape , model , source_table , oversample = 1 ) : image = np . zeros ( shape , dtype = np . float64 ) y , x = np . indices ( shape ) params_to_set = [ ] for param in source_table . colnames : if param in model . param_names : params_to_set . append ( param ) init_params = { param : getatt... | Make an image containing sources generated from a user - specified model . |
54,617 | def make_4gaussians_image ( noise = True ) : table = Table ( ) table [ 'amplitude' ] = [ 50 , 70 , 150 , 210 ] table [ 'x_mean' ] = [ 160 , 25 , 150 , 90 ] table [ 'y_mean' ] = [ 70 , 40 , 25 , 60 ] table [ 'x_stddev' ] = [ 15.2 , 5.1 , 3. , 8.1 ] table [ 'y_stddev' ] = [ 2.6 , 2.5 , 3. , 4.7 ] table [ 'theta' ] = np .... | Make an example image containing four 2D Gaussians plus a constant background . |
54,618 | def make_100gaussians_image ( noise = True ) : n_sources = 100 flux_range = [ 500 , 1000 ] xmean_range = [ 0 , 500 ] ymean_range = [ 0 , 300 ] xstddev_range = [ 1 , 5 ] ystddev_range = [ 1 , 5 ] params = OrderedDict ( [ ( 'flux' , flux_range ) , ( 'x_mean' , xmean_range ) , ( 'y_mean' , ymean_range ) , ( 'x_stddev' , x... | Make an example image containing 100 2D Gaussians plus a constant background . |
54,619 | def make_wcs ( shape , galactic = False ) : wcs = WCS ( naxis = 2 ) rho = np . pi / 3. scale = 0.1 / 3600. if astropy_version < '3.1' : wcs . _naxis1 = shape [ 1 ] wcs . _naxis2 = shape [ 0 ] else : wcs . pixel_shape = shape wcs . wcs . crpix = [ shape [ 1 ] / 2 , shape [ 0 ] / 2 ] wcs . wcs . crval = [ 197.8925 , - 1.... | Create a simple celestial WCS object in either the ICRS or Galactic coordinate frame . |
54,620 | def make_imagehdu ( data , wcs = None ) : data = np . asanyarray ( data ) if data . ndim != 2 : raise ValueError ( 'data must be a 2D array' ) if wcs is not None : header = wcs . to_header ( ) else : header = None return fits . ImageHDU ( data , header = header ) | Create a FITS ~astropy . io . fits . ImageHDU containing the input 2D image . |
54,621 | def centroid_com ( data , mask = None ) : data = data . astype ( np . float ) if mask is not None and mask is not np . ma . nomask : mask = np . asarray ( mask , dtype = bool ) if data . shape != mask . shape : raise ValueError ( 'data and mask must have the same shape.' ) data [ mask ] = 0. badidx = ~ np . isfinite ( ... | Calculate the centroid of an n - dimensional array as its center of mass determined from moments . |
54,622 | def gaussian1d_moments ( data , mask = None ) : if np . any ( ~ np . isfinite ( data ) ) : data = np . ma . masked_invalid ( data ) warnings . warn ( 'Input data contains input values (e.g. NaNs or infs), ' 'which were automatically masked.' , AstropyUserWarning ) else : data = np . ma . array ( data ) if mask is not N... | Estimate 1D Gaussian parameters from the moments of 1D data . |
54,623 | def fit_2dgaussian ( data , error = None , mask = None ) : from . . morphology import data_properties data = np . ma . asanyarray ( data ) if mask is not None and mask is not np . ma . nomask : mask = np . asanyarray ( mask ) if data . shape != mask . shape : raise ValueError ( 'data and mask must have the same shape.'... | Fit a 2D Gaussian plus a constant to a 2D image . |
54,624 | def centroid_1dg ( data , error = None , mask = None ) : data = np . ma . asanyarray ( data ) if mask is not None and mask is not np . ma . nomask : mask = np . asanyarray ( mask ) if data . shape != mask . shape : raise ValueError ( 'data and mask must have the same shape.' ) data . mask |= mask if np . any ( ~ np . i... | Calculate the centroid of a 2D array by fitting 1D Gaussians to the marginal x and y distributions of the array . |
54,625 | def centroid_sources ( data , xpos , ypos , box_size = 11 , footprint = None , error = None , mask = None , centroid_func = centroid_com ) : xpos = np . atleast_1d ( xpos ) ypos = np . atleast_1d ( ypos ) if xpos . ndim != 1 : raise ValueError ( 'xpos must be a 1D array.' ) if ypos . ndim != 1 : raise ValueError ( 'ypo... | Calculate the centroid of sources at the defined positions . |
54,626 | def evaluate ( x , y , constant , amplitude , x_mean , y_mean , x_stddev , y_stddev , theta ) : model = Const2D ( constant ) ( x , y ) + Gaussian2D ( amplitude , x_mean , y_mean , x_stddev , y_stddev , theta ) ( x , y ) return model | Two dimensional Gaussian plus constant function . |
54,627 | def evaluate ( self , x , y , flux , x_0 , y_0 ) : x = ( x - x_0 + 0.5 + self . prf_shape [ 1 ] // 2 ) . astype ( 'int' ) y = ( y - y_0 + 0.5 + self . prf_shape [ 0 ] // 2 ) . astype ( 'int' ) y_sub , x_sub = subpixel_indices ( ( y_0 , x_0 ) , self . subsampling ) x_bound = np . logical_or ( x < 0 , x >= self . prf_sha... | Discrete PRF model evaluation . |
54,628 | def _reproject ( wcs1 , wcs2 ) : import gwcs forward_origin = [ ] if isinstance ( wcs1 , fitswcs . WCS ) : forward = wcs1 . all_pix2world forward_origin = [ 0 ] elif isinstance ( wcs2 , gwcs . wcs . WCS ) : forward = wcs1 . forward_transform else : raise ValueError ( 'wcs1 must be an astropy.wcs.WCS or ' 'gwcs.wcs.WCS ... | Perform the forward transformation of wcs1 followed by the inverse transformation of wcs2 . |
54,629 | def get_version_info ( ) : from astropy import __version__ astropy_version = __version__ from photutils import __version__ photutils_version = __version__ return 'astropy: {0}, photutils: {1}' . format ( astropy_version , photutils_version ) | Return astropy and photutils versions . |
54,630 | def calc_total_error ( data , bkg_error , effective_gain ) : data = np . asanyarray ( data ) bkg_error = np . asanyarray ( bkg_error ) inputs = [ data , bkg_error , effective_gain ] has_unit = [ hasattr ( x , 'unit' ) for x in inputs ] use_units = all ( has_unit ) if any ( has_unit ) and not use_units : raise ValueErro... | Calculate a total error array combining a background - only error array with the Poisson noise of sources . |
54,631 | def to_sky ( self , wcs , mode = 'all' ) : sky_params = self . _to_sky_params ( wcs , mode = mode ) return SkyRectangularAperture ( ** sky_params ) | Convert the aperture to a SkyRectangularAperture object defined in celestial coordinates . |
54,632 | def to_sky ( self , wcs , mode = 'all' ) : sky_params = self . _to_sky_params ( wcs , mode = mode ) return SkyRectangularAnnulus ( ** sky_params ) | Convert the aperture to a SkyRectangularAnnulus object defined in celestial coordinates . |
54,633 | def to_pixel ( self , wcs , mode = 'all' ) : pixel_params = self . _to_pixel_params ( wcs , mode = mode ) return RectangularAperture ( ** pixel_params ) | Convert the aperture to a RectangularAperture object defined in pixel coordinates . |
54,634 | def to_pixel ( self , wcs , mode = 'all' ) : pixel_params = self . _to_pixel_params ( wcs , mode = mode ) return RectangularAnnulus ( ** pixel_params ) | Convert the aperture to a RectangularAnnulus object defined in pixel coordinates . |
54,635 | def _py2intround ( a ) : data = np . asanyarray ( a ) value = np . where ( data >= 0 , np . floor ( data + 0.5 ) , np . ceil ( data - 0.5 ) ) . astype ( int ) if not hasattr ( a , '__iter__' ) : value = np . asscalar ( value ) return value | Round the input to the nearest integer . |
54,636 | def _interpolate_missing_data ( data , mask , method = 'cubic' ) : from scipy import interpolate data_interp = np . array ( data , copy = True ) if len ( data_interp . shape ) != 2 : raise ValueError ( 'data must be a 2D array.' ) if mask . shape != data . shape : raise ValueError ( 'mask and data must have the same sh... | Interpolate missing data as identified by the mask keyword . |
54,637 | def _fit_star ( self , epsf , star , fitter , fitter_kwargs , fitter_has_fit_info , fit_boxsize ) : if fit_boxsize is not None : try : xcenter , ycenter = star . cutout_center large_slc , small_slc = overlap_slices ( star . shape , fit_boxsize , ( ycenter , xcenter ) , mode = 'strict' ) except ( PartialOverlapError , N... | Fit an ePSF model to a single star . |
54,638 | def _init_img_params ( param ) : if param is not None : param = np . atleast_1d ( param ) if len ( param ) == 1 : param = np . repeat ( param , 2 ) return param | Initialize 2D image - type parameters that can accept either a single or two values . |
54,639 | def _create_initial_epsf ( self , stars ) : oversampling = self . oversampling shape = self . shape if shape is not None : shape = np . atleast_1d ( shape ) . astype ( int ) if len ( shape ) == 1 : shape = np . repeat ( shape , 2 ) else : x_shape = np . int ( np . ceil ( stars . _max_shape [ 1 ] * oversampling [ 0 ] ) ... | Create an initial EPSFModel object . |
54,640 | def _resample_residual ( self , star , epsf ) : x = epsf . _oversampling [ 0 ] * star . _xidx_centered y = epsf . _oversampling [ 1 ] * star . _yidx_centered epsf_xcenter , epsf_ycenter = epsf . origin xidx = _py2intround ( x + epsf_xcenter ) yidx = _py2intround ( y + epsf_ycenter ) mask = np . logical_and ( np . logic... | Compute a normalized residual image in the oversampled ePSF grid . |
54,641 | def _resample_residuals ( self , stars , epsf ) : shape = ( stars . n_good_stars , epsf . shape [ 0 ] , epsf . shape [ 1 ] ) star_imgs = np . zeros ( shape ) for i , star in enumerate ( stars . all_good_stars ) : star_imgs [ i , : , : ] = self . _resample_residual ( star , epsf ) return star_imgs | Compute normalized residual images for all the input stars . |
54,642 | def _smooth_epsf ( self , epsf_data ) : from scipy . ndimage import convolve if self . smoothing_kernel is None : return epsf_data elif self . smoothing_kernel == 'quartic' : kernel = np . array ( [ [ + 0.041632 , - 0.080816 , 0.078368 , - 0.080816 , + 0.041632 ] , [ - 0.080816 , - 0.019592 , 0.200816 , - 0.019592 , - ... | Smooth the ePSF array by convolving it with a kernel . |
54,643 | def _recenter_epsf ( self , epsf_data , epsf , centroid_func = centroid_com , box_size = 5 , maxiters = 20 , center_accuracy = 1.0e-4 ) : epsf = EPSFModel ( data = epsf_data , origin = epsf . origin , normalize = False , oversampling = epsf . oversampling ) epsf . fill_value = 0.0 xcenter , ycenter = epsf . origin dx_t... | Calculate the center of the ePSF data and shift the data so the ePSF center is at the center of the ePSF data array . |
54,644 | def _build_epsf_step ( self , stars , epsf = None ) : if len ( stars ) < 1 : raise ValueError ( 'stars must contain at least one EPSFStar or ' 'LinkedEPSFStar object.' ) if epsf is None : epsf = self . _create_initial_epsf ( stars ) else : epsf = copy . deepcopy ( epsf ) residuals = self . _resample_residuals ( stars ,... | A single iteration of improving an ePSF . |
54,645 | def build_epsf ( self , stars , init_epsf = None ) : iter_num = 0 center_dist_sq = self . center_accuracy_sq + 1. centers = stars . cutout_center_flat n_stars = stars . n_stars fit_failed = np . zeros ( n_stars , dtype = bool ) dx_dy = np . zeros ( ( n_stars , 2 ) , dtype = np . float ) epsf = init_epsf dt = 0. while (... | Iteratively build an ePSF from star cutouts . |
54,646 | def _set_oversampling ( self , value ) : try : value = np . atleast_1d ( value ) . astype ( float ) if len ( value ) == 1 : value = np . repeat ( value , 2 ) except ValueError : raise ValueError ( 'Oversampling factors must be float' ) if np . any ( value <= 0 ) : raise ValueError ( 'Oversampling factors must be greate... | This is a private method because it s used in the initializer by the oversampling |
54,647 | def evaluate ( self , x , y , flux , x_0 , y_0 , use_oversampling = True ) : if use_oversampling : xi = self . _oversampling [ 0 ] * ( np . asarray ( x ) - x_0 ) yi = self . _oversampling [ 1 ] * ( np . asarray ( y ) - y_0 ) else : xi = np . asarray ( x ) - x_0 yi = np . asarray ( y ) - y_0 xi += self . _x_origin yi +=... | Evaluate the model on some input variables and provided model parameters . |
54,648 | def _find_bounds_1d ( data , x ) : idx = np . searchsorted ( data , x ) if idx == 0 : idx0 = 0 elif idx == len ( data ) : idx0 = idx - 2 else : idx0 = idx - 1 return idx0 | Find the index of the lower bound where x should be inserted into a to maintain order . |
54,649 | def _bilinear_interp ( xyref , zref , xi , yi ) : if len ( xyref ) != 4 : raise ValueError ( 'xyref must contain only 4 (x, y) pairs' ) if zref . shape [ 0 ] != 4 : raise ValueError ( 'zref must have a length of 4 on the first ' 'axis.' ) xyref = [ tuple ( i ) for i in xyref ] idx = sorted ( range ( len ( xyref ) ) , k... | Perform bilinear interpolation of four 2D arrays located at points on a regular grid . |
54,650 | def evaluate ( self , x , y , flux , x_0 , y_0 ) : if not np . isscalar ( x_0 ) : x_0 = x_0 [ 0 ] if not np . isscalar ( y_0 ) : y_0 = y_0 [ 0 ] if ( x_0 < self . _xgrid_min or x_0 > self . _xgrid_max or y_0 < self . _ygrid_min or y_0 > self . _ygrid_max ) : self . _ref_indices = np . argsort ( np . hypot ( self . _gri... | Evaluate the GriddedPSFModel for the input parameters . |
54,651 | def evaluate ( self , x , y , flux , x_0 , y_0 , sigma ) : return ( flux / 4 * ( ( self . _erf ( ( x - x_0 + 0.5 ) / ( np . sqrt ( 2 ) * sigma ) ) - self . _erf ( ( x - x_0 - 0.5 ) / ( np . sqrt ( 2 ) * sigma ) ) ) * ( self . _erf ( ( y - y_0 + 0.5 ) / ( np . sqrt ( 2 ) * sigma ) ) - self . _erf ( ( y - y_0 - 0.5 ) / (... | Model function Gaussian PSF model . |
54,652 | def evaluate ( self , x , y , flux , x_0 , y_0 ) : if self . xname is None : dx = x - x_0 else : dx = x setattr ( self . psfmodel , self . xname , x_0 ) if self . xname is None : dy = y - y_0 else : dy = y setattr ( self . psfmodel , self . yname , y_0 ) if self . fluxname is None : return ( flux * self . _psf_scale_fa... | The evaluation function for PRFAdapter . |
54,653 | def _isophote_list_to_table ( isophote_list ) : properties = OrderedDict ( ) properties [ 'sma' ] = 'sma' properties [ 'intens' ] = 'intens' properties [ 'int_err' ] = 'intens_err' properties [ 'eps' ] = 'ellipticity' properties [ 'ellip_err' ] = 'ellipticity_err' properties [ 'pa' ] = 'pa' properties [ 'pa_err' ] = 'p... | Convert an ~photutils . isophote . IsophoteList instance to a ~astropy . table . QTable . |
54,654 | def _compute_fluxes ( self ) : sma = self . sample . geometry . sma x0 = self . sample . geometry . x0 y0 = self . sample . geometry . y0 xsize = self . sample . image . shape [ 1 ] ysize = self . sample . image . shape [ 0 ] imin = max ( 0 , int ( x0 - sma - 0.5 ) - 1 ) jmin = max ( 0 , int ( y0 - sma - 0.5 ) - 1 ) im... | Compute integrated flux inside ellipse as well as inside a circle defined with the same semimajor axis . |
54,655 | def _compute_deviations ( self , sample , n ) : try : coeffs = fit_first_and_second_harmonics ( self . sample . values [ 0 ] , self . sample . values [ 2 ] ) coeffs = coeffs [ 0 ] model = first_and_second_harmonic_function ( self . sample . values [ 0 ] , coeffs ) residual = self . sample . values [ 2 ] - model c = fit... | Compute deviations from a perfect ellipse based on the amplitudes and errors for harmonic n . Note that we first subtract the first and second harmonics from the raw data . |
54,656 | def _compute_errors ( self ) : try : coeffs = fit_first_and_second_harmonics ( self . sample . values [ 0 ] , self . sample . values [ 2 ] ) covariance = coeffs [ 1 ] coeffs = coeffs [ 0 ] model = first_and_second_harmonic_function ( self . sample . values [ 0 ] , coeffs ) residual_rms = np . std ( self . sample . valu... | Compute parameter errors based on the diagonal of the covariance matrix of the four harmonic coefficients for harmonics n = 1 and n = 2 . |
54,657 | def fix_geometry ( self , isophote ) : self . sample . geometry . eps = isophote . sample . geometry . eps self . sample . geometry . pa = isophote . sample . geometry . pa self . sample . geometry . x0 = isophote . sample . geometry . x0 self . sample . geometry . y0 = isophote . sample . geometry . y0 | Fix the geometry of a problematic isophote to be identical to the input isophote . |
54,658 | def get_closest ( self , sma ) : index = ( np . abs ( self . sma - sma ) ) . argmin ( ) return self . _list [ index ] | Return the ~photutils . isophote . Isophote instance that has the closest semimajor axis length to the input semimajor axis . |
54,659 | def interpolate_masked_data ( data , mask , error = None , background = None ) : if data . shape != mask . shape : raise ValueError ( 'data and mask must have the same shape' ) data_out = np . copy ( data ) mask_idx = mask . nonzero ( ) if mask_idx [ 0 ] . size == 0 : raise ValueError ( 'All items in data are masked' )... | Interpolate over masked pixels in data and optional error or background images . |
54,660 | def ThreadsWithRunningExecServers ( self ) : socket_dir = '/tmp/pyringe_%s' % self . inferior . pid if os . path . isdir ( socket_dir ) : return [ int ( fname [ : - 9 ] ) for fname in os . listdir ( socket_dir ) if fname . endswith ( '.execsock' ) ] return [ ] | Returns a list of tids of inferior threads with open exec servers . |
54,661 | def SendToExecSocket ( self , code , tid = None ) : response = self . _SendToExecSocketRaw ( json . dumps ( code ) , tid ) return json . loads ( response ) | Inject python code into exec socket . |
54,662 | def CloseExecSocket ( self , tid = None ) : response = self . _SendToExecSocketRaw ( '__kill__' , tid ) if response != '__kill_ack__' : logging . warning ( 'May not have succeeded in closing socket, make sure ' 'using execsocks().' ) | Send closing request to exec socket . |
54,663 | def Backtrace ( self , to_string = False ) : if self . inferior . is_running : res = self . inferior . Backtrace ( ) if to_string : return res print res else : logging . error ( 'Not attached to any process.' ) | Get a backtrace of the current position . |
54,664 | def ListThreads ( self ) : if self . inferior . is_running : return self . inferior . threads logging . error ( 'Not attached to any process.' ) return [ ] | List the currently running python threads . |
54,665 | def extract_filename ( self ) : globals_gdbval = self . _gdbval [ 'f_globals' ] . cast ( GdbCache . DICT ) global_dict = libpython . PyDictObjectPtr ( globals_gdbval ) for key , value in global_dict . iteritems ( ) : if str ( key . proxyval ( set ( ) ) ) == '__file__' : return str ( value . proxyval ( set ( ) ) ) | Alternative way of getting the executed file which inspects globals . |
54,666 | def _UnserializableObjectFallback ( self , obj ) : if isinstance ( obj , libpython . PyInstanceObjectPtr ) : in_class = obj . pyop_field ( 'in_class' ) result_dict = in_class . pyop_field ( 'cl_dict' ) . proxyval ( set ( ) ) instanceproxy = obj . proxyval ( set ( ) ) result_dict . update ( instanceproxy . attrdict ) re... | Handles sanitizing of unserializable objects for Json . |
54,667 | def _AcceptRPC ( self ) : request = self . _ReadObject ( ) if request [ 'func' ] == '__kill__' : self . ClearBreakpoints ( ) self . _WriteObject ( '__kill_ack__' ) return False if 'func' not in request or request [ 'func' ] . startswith ( '_' ) : raise RpcException ( 'Not a valid public API function.' ) rpc_result = ge... | Reads RPC request from stdin and processes it writing result to stdout . |
54,668 | def _UnpackGdbVal ( self , gdb_value ) : val_type = gdb_value . type . code if val_type == gdb . TYPE_CODE_INT or val_type == gdb . TYPE_CODE_ENUM : return int ( gdb_value ) if val_type == gdb . TYPE_CODE_VOID : return None if val_type == gdb . TYPE_CODE_PTR : return long ( gdb_value ) if val_type == gdb . TYPE_CODE_AR... | Unpacks gdb . Value objects and returns the best - matched python object . |
54,669 | def EnsureGdbPosition ( self , pid , tid , frame_depth ) : position = [ pid , tid , frame_depth ] if not pid : return if not self . IsAttached ( ) : try : self . Attach ( position ) except gdb . error as exc : raise PositionUnavailableException ( exc . message ) if gdb . selected_inferior ( ) . pid != pid : self . Deta... | Make sure our position matches the request . |
54,670 | def IsSymbolFileSane ( self , position ) : pos = [ position [ 0 ] , None , None ] self . EnsureGdbPosition ( * pos ) try : if GdbCache . DICT and GdbCache . TYPE and GdbCache . INTERP_HEAD : tstate = GdbCache . INTERP_HEAD [ 'tstate_head' ] tstate [ 'thread_id' ] frame = tstate [ 'frame' ] frame_attrs = [ 'f_back' , 'f... | Performs basic sanity check by trying to look up a bunch of symbols . |
54,671 | def Detach ( self ) : if not self . IsAttached ( ) : return None pid = gdb . selected_inferior ( ) . pid self . Interrupt ( [ pid , None , None ] ) self . Continue ( [ pid , None , None ] ) result = gdb . execute ( 'detach' , to_string = True ) if not result : return None return result | Detaches from the inferior . If not attached this is a no - op . |
54,672 | def Call ( self , position , function_call ) : self . EnsureGdbPosition ( position [ 0 ] , None , None ) if not gdb . selected_thread ( ) . is_stopped ( ) : self . Interrupt ( position ) result_value = gdb . parse_and_eval ( function_call ) return self . _UnpackGdbVal ( result_value ) | Perform a function call in the inferior . |
54,673 | def ExecuteRaw ( self , position , command ) : self . EnsureGdbPosition ( position [ 0 ] , None , None ) return gdb . execute ( command , to_string = True ) | Send a command string to gdb . |
54,674 | def _GetGdbThreadMapping ( self , position ) : if len ( gdb . selected_inferior ( ) . threads ( ) ) == 1 : return { position [ 1 ] : 1 } thread_line_regexp = r'\s*\**\s*([0-9]+)\s+[a-zA-Z]+\s+([x0-9a-fA-F]+)\s.*' output = gdb . execute ( 'info threads' , to_string = True ) matches = [ re . match ( thread_line_regexp , ... | Gets a mapping from python tid to gdb thread num . |
54,675 | def _Inject ( self , position , call ) : self . EnsureGdbPosition ( position [ 0 ] , position [ 1 ] , None ) self . ClearBreakpoints ( ) self . _AddThreadSpecificBreakpoint ( position ) gdb . parse_and_eval ( '%s = 1' % GdbCache . PENDINGCALLS_TO_DO ) gdb . parse_and_eval ( '%s = 1' % GdbCache . PENDINGBUSY ) try : sel... | Injects evaluation of call in a safe location in the inferior . |
54,676 | def _BacktraceFromFramePtr ( self , frame_ptr ) : frame_objs = [ PyFrameObjectPtr ( frame ) for frame in self . _IterateChainedList ( frame_ptr , 'f_back' ) ] frame_objs . reverse ( ) tb_strings = [ 'Traceback (most recent call last):' ] for frame in frame_objs : line_string = ( ' File "%s", line %s, in %s' % ( frame ... | Assembles and returns what looks exactly like python s backtraces . |
54,677 | def Kill ( self ) : try : if self . is_running : self . Detach ( ) if self . _Execute ( '__kill__' ) == '__kill_ack__' : time . sleep ( 0.1 ) except ( TimeoutError , ProxyError ) : logging . debug ( 'Termination request not acknowledged, killing gdb.' ) if self . is_running : os . kill ( self . _process . pid , signal ... | Send death pill to Gdb and forcefully kill it if that doesn t work . |
54,678 | def Version ( ) : output = subprocess . check_output ( [ 'gdb' , '--version' ] ) . split ( '\n' ) [ 0 ] major = None minor = None micro = None for potential_versionstring in output . split ( ) : version = re . split ( '[^0-9]' , potential_versionstring ) try : major = int ( version [ 0 ] ) except ( IndexError , ValueEr... | Gets the version of gdb as a 3 - tuple . |
54,679 | def _JsonDecodeDict ( self , data ) : rv = { } for key , value in data . iteritems ( ) : if isinstance ( key , unicode ) : key = self . _TryStr ( key ) if isinstance ( value , unicode ) : value = self . _TryStr ( value ) elif isinstance ( value , list ) : value = self . _JsonDecodeList ( value ) rv [ key ] = value if '... | Json object decode hook that automatically converts unicode objects . |
54,680 | def _Execute ( self , funcname , * args , ** kwargs ) : wait_for_completion = kwargs . get ( 'wait_for_completion' , False ) rpc_dict = { 'func' : funcname , 'args' : args } self . _Send ( json . dumps ( rpc_dict ) ) timeout = TIMEOUT_FOREVER if wait_for_completion else TIMEOUT_DEFAULT result_string = self . _Recv ( ti... | Send an RPC request to the gdb - internal python . |
54,681 | def _Recv ( self , timeout ) : buf = '' wait_for_line = timeout is TIMEOUT_FOREVER deadline = time . time ( ) + ( timeout if not wait_for_line else 0 ) def TimeLeft ( ) : return max ( 1000 * ( deadline - time . time ( ) ) , 0 ) continue_reading = True while continue_reading : poll_timeout = None if wait_for_line else T... | Receive output from gdb . |
54,682 | def needsattached ( func ) : @ functools . wraps ( func ) def wrap ( self , * args , ** kwargs ) : if not self . attached : raise PositionError ( 'Not attached to any process.' ) return func ( self , * args , ** kwargs ) return wrap | Decorator to prevent commands from being used when not attached . |
54,683 | def Reinit ( self , pid , auto_symfile_loading = True ) : self . ShutDownGdb ( ) self . __init__ ( pid , auto_symfile_loading , architecture = self . arch ) | Reinitializes the object with a new pid . |
54,684 | def InjectString ( self , codestring , wait_for_completion = True ) : if self . inferior . is_running and self . inferior . gdb . IsAttached ( ) : try : self . inferior . gdb . InjectString ( self . inferior . position , codestring , wait_for_completion = wait_for_completion ) except RuntimeError : exc_type , exc_value... | Try to inject python code into current thread . |
54,685 | def field ( self , name ) : if self . is_null ( ) : raise NullPyObjectPtr ( self ) if name == 'ob_type' : pyo_ptr = self . _gdbval . cast ( PyObjectPtr . get_gdb_type ( ) ) return pyo_ptr . dereference ( ) [ name ] if name == 'ob_size' : try : return self . _gdbval . dereference ( ) [ name ] except RuntimeError : retur... | Get the gdb . Value for the given field within the PyObject coping with some python 2 versus python 3 differences . |
54,686 | def write_repr ( self , out , visited ) : return out . write ( repr ( self . proxyval ( visited ) ) ) | Write a string representation of the value scraped from the inferior process to out a file - like object . |
54,687 | def from_pyobject_ptr ( cls , gdbval ) : try : p = PyObjectPtr ( gdbval ) cls = cls . subclass_from_type ( p . type ( ) ) return cls ( gdbval , cast_to = cls . get_gdb_type ( ) ) except RuntimeError : pass return cls ( gdbval ) | Try to locate the appropriate derived class dynamically and cast the pointer accordingly . |
54,688 | def proxyval ( self , visited ) : if self . as_address ( ) in visited : return ProxyAlreadyVisited ( '<...>' ) visited . add ( self . as_address ( ) ) pyop_attr_dict = self . get_attr_dict ( ) if pyop_attr_dict : attr_dict = pyop_attr_dict . proxyval ( visited ) else : attr_dict = { } tp_name = self . safe_tp_name ( ) ... | Support for new - style classes . |
54,689 | def addr2line ( self , addrq ) : co_lnotab = self . pyop_field ( 'co_lnotab' ) . proxyval ( set ( ) ) lineno = int_from_int ( self . field ( 'co_firstlineno' ) ) addr = 0 for addr_incr , line_incr in zip ( co_lnotab [ : : 2 ] , co_lnotab [ 1 : : 2 ] ) : addr += ord ( addr_incr ) if addr > addrq : return lineno lineno +... | Get the line number for a given bytecode offset |
54,690 | def current_line ( self ) : if self . is_optimized_out ( ) : return '(frame information optimized out)' with open ( self . filename ( ) , 'r' ) as f : all_lines = f . readlines ( ) return all_lines [ self . current_line_num ( ) - 1 ] | Get the text of the current source line as a string with a trailing newline character |
54,691 | def select ( self ) : if not hasattr ( self . _gdbframe , 'select' ) : print ( 'Unable to select frame: ' 'this build of gdb does not expose a gdb.Frame.select method' ) return False self . _gdbframe . select ( ) return True | If supported select this frame and return True ; return False if unsupported |
54,692 | def get_index ( self ) : index = 0 iter_frame = self while iter_frame . newer ( ) : index += 1 iter_frame = iter_frame . newer ( ) return index | Calculate index of frame starting at 0 for the newest frame within this thread |
54,693 | def is_evalframeex ( self ) : if self . _gdbframe . name ( ) == 'PyEval_EvalFrameEx' : if self . _gdbframe . type ( ) == gdb . NORMAL_FRAME : return True return False | Is this a PyEval_EvalFrameEx frame? |
54,694 | def get_selected_python_frame ( cls ) : frame = cls . get_selected_frame ( ) while frame : if frame . is_evalframeex ( ) : return frame frame = frame . older ( ) return None | Try to obtain the Frame for the python code in the selected frame or None |
54,695 | def ListCommands ( self ) : print 'Available commands:' commands = dict ( self . commands ) for plugin in self . plugins : commands . update ( plugin . commands ) for com in sorted ( commands ) : if not com . startswith ( '_' ) : self . PrintHelpTextLine ( com , commands [ com ] ) | Print a list of currently available commands and their descriptions . |
54,696 | def StatusLine ( self ) : pid = self . inferior . pid curthread = None threadnum = 0 if pid : if not self . inferior . is_running : logging . warning ( 'Inferior is not running.' ) self . Detach ( ) pid = None else : try : if not self . inferior . attached : self . inferior . StartGdb ( ) curthread = self . inferior . ... | Generate the colored line indicating plugin status . |
54,697 | def Attach ( self , pid ) : if self . inferior . is_running : answer = raw_input ( 'Already attached to process ' + str ( self . inferior . pid ) + '. Detach? [y]/n ' ) if answer and answer != 'y' and answer != 'yes' : return None self . Detach ( ) for plugin in self . plugins : plugin . position = None self . inferior... | Attach to the process with the given pid . |
54,698 | def StartGdb ( self ) : if self . inferior . is_running : self . inferior . ShutDownGdb ( ) program_arg = 'program %d ' % self . inferior . pid else : program_arg = '' os . system ( 'gdb ' + program_arg + ' ' . join ( self . gdb_args ) ) reset_position = raw_input ( 'Reset debugger position? [y]/n ' ) if not reset_posi... | Hands control over to a new gdb process . |
54,699 | def __get_node ( self , word ) : node = self . root for c in word : try : node = node . children [ c ] except KeyError : return None return node | Private function retrieving a final node of trie for given word |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.