idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
24,900 | def panset_cb ( self , setting , value , chviewer , info ) : return self . panset ( chviewer , info . chinfo ) | This callback is called when a channel window is panned . | 34 | 12 |
24,901 | def timer_tick ( self ) : # TODO: should exceptions thrown from this be caught and ignored self . process_timers ( ) delta = datetime . timedelta ( milliseconds = self . base_interval_msec ) self . _timeout = IOLoop . current ( ) . add_timeout ( delta , self . timer_tick ) | Callback executed every self . base_interval_msec to check timer expirations . | 74 | 19 |
24,902 | def select_cb ( self , viewer , event , data_x , data_y ) : if not ( self . _cmxoff <= data_x < self . _cmwd ) : # need to click within the width of the bar return i = int ( data_y / ( self . _cmht + self . _cmsep ) ) if 0 <= i < len ( self . cm_names ) : name = self . cm_names [ i ] msg = "cmap => '%s'" % ( name ) self . logger . info ( msg ) channel = self . fv . get_channel_info ( ) if channel is not None : viewer = channel . fitsimage #viewer.onscreen_message(msg, delay=0.5) viewer . set_color_map ( name ) | Called when the user clicks on the color bar viewer . Calculate the index of the color bar they clicked on and set that color map in the current channel viewer . | 174 | 34 |
24,903 | def scroll_cb ( self , viewer , direction , amt , data_x , data_y ) : bd = viewer . get_bindings ( ) direction = bd . get_direction ( direction ) pan_x , pan_y = viewer . get_pan ( ) [ : 2 ] qty = self . _cmsep * amt * self . settings . get ( 'cbar_pan_accel' , 1.0 ) if direction == 'up' : pan_y -= qty else : pan_y += qty pan_y = min ( max ( pan_y , 0 ) , self . _max_y ) viewer . set_pan ( pan_x , pan_y ) | Called when the user scrolls in the color bar viewer . Pan up or down to show additional bars . | 154 | 21 |
24,904 | def rebuild_cmaps ( self ) : self . logger . info ( "building color maps image" ) ht , wd , sep = self . _cmht , self . _cmwd , self . _cmsep viewer = self . p_view # put the canvas into pick mode canvas = viewer . get_canvas ( ) canvas . delete_all_objects ( ) # get the list of color maps cm_names = self . cm_names num_cmaps = len ( cm_names ) viewer . configure_surface ( 500 , ( ht + sep ) * num_cmaps ) # create a bunch of color bars and make one large compound object # with callbacks for clicking on individual color bars l2 = [ ] ColorBar = canvas . get_draw_class ( 'drawablecolorbar' ) Text = canvas . get_draw_class ( 'text' ) #ch_rgbmap = chviewer.get_rgbmap() #dist = ch_rgbmap.get_dist() dist = None #imap = ch_rgbmap.get_imap() logger = viewer . get_logger ( ) for i , name in enumerate ( cm_names ) : rgbmap = RGBMap . RGBMapper ( logger , dist = dist ) rgbmap . set_cmap ( cmap . get_cmap ( name ) ) #rgbmap.set_imap(imap) x1 , y1 = self . _cmxoff , i * ( ht + sep ) x2 , y2 = x1 + wd , y1 + ht cbar = ColorBar ( x1 , y1 , x2 , y2 , cm_name = name , showrange = False , rgbmap = rgbmap , coord = 'window' ) l2 . append ( cbar ) l2 . append ( Text ( x2 + sep , y2 , name , color = 'white' , fontsize = 16 , coord = 'window' ) ) Compound = canvas . get_draw_class ( 'compoundobject' ) obj = Compound ( * l2 ) canvas . add ( obj ) self . _max_y = y2 rgb_img = self . p_view . get_image_as_array ( ) self . r_image . set_data ( rgb_img ) | Builds a color RGB image containing color bars of all the possible color maps and their labels . | 503 | 19 |
24,905 | def record_sizes ( self ) : for rec in self . node . values ( ) : w = rec . widget wd , ht = w . get_size ( ) rec . params . update ( dict ( name = rec . name , width = wd , height = ht ) ) if rec . kind in ( 'hpanel' , 'vpanel' ) : sizes = w . get_sizes ( ) rec . params . update ( dict ( sizes = sizes ) ) if rec . kind in ( 'ws' , ) : # record ws type # TODO: record positions of subwindows rec . params . update ( dict ( wstype = rec . ws . wstype ) ) if rec . kind == 'top' : # record position for top-level widgets as well x , y = w . get_pos ( ) if x is not None and y is not None : # we don't always get reliable information about position rec . params . update ( dict ( xpos = x , ypos = y ) ) | Record sizes of all container widgets in the layout . The sizes are recorded in the params mappings in the layout . | 221 | 23 |
24,906 | def help ( self , * args ) : if len ( args ) == 0 : return help_msg which = args [ 0 ] . lower ( ) if which == 'ginga' : method = args [ 1 ] _method = getattr ( self . fv , method ) return _method . __doc__ elif which == 'channel' : chname = args [ 1 ] method = args [ 2 ] chinfo = self . fv . get_channel ( chname ) _method = getattr ( chinfo . viewer , method ) return _method . __doc__ else : return ( "Please use 'help ginga <method>' or " "'help channel <chname> <method>'" ) | Get help for a remote interface method . | 151 | 8 |
24,907 | def load_buffer ( self , imname , chname , img_buf , dims , dtype , header , metadata , compressed ) : self . logger . info ( "received image data len=%d" % ( len ( img_buf ) ) ) # Unpack the data try : # Uncompress data if necessary decompress = metadata . get ( 'decompress' , None ) if compressed or ( decompress == 'bz2' ) : img_buf = bz2 . decompress ( img_buf ) # dtype string works for most instances if dtype == '' : dtype = numpy . float32 byteswap = metadata . get ( 'byteswap' , False ) # Create image container image = AstroImage . AstroImage ( logger = self . logger ) image . load_buffer ( img_buf , dims , dtype , byteswap = byteswap , metadata = metadata ) image . update_keywords ( header ) image . set ( name = imname , path = None ) except Exception as e : # Some kind of error unpacking the data errmsg = "Error creating image data for '%s': %s" % ( imname , str ( e ) ) self . logger . error ( errmsg ) raise GingaPlugin . PluginError ( errmsg ) # Display the image channel = self . fv . gui_call ( self . fv . get_channel_on_demand , chname ) # Note: this little hack needed to let window resize in time for # file to auto-size properly self . fv . gui_do ( self . fv . change_channel , channel . name ) self . fv . gui_do ( self . fv . add_image , imname , image , chname = channel . name ) return 0 | Display a FITS image buffer . | 385 | 7 |
24,908 | def use ( name ) : global toolkit , family name = name . lower ( ) if name . startswith ( 'choose' ) : pass elif name . startswith ( 'qt' ) or name . startswith ( 'pyside' ) : family = 'qt' if name == 'qt' : name = 'qt4' assert name in ( 'qt4' , 'pyside' , 'qt5' ) , ToolKitError ( "ToolKit '%s' not supported!" % ( name ) ) elif name . startswith ( 'gtk' ) : # default for "gtk" is gtk3 if name in ( 'gtk' , 'gtk3' ) : name = 'gtk3' family = 'gtk3' elif name in ( 'gtk2' , ) : family = 'gtk' assert name in ( 'gtk2' , 'gtk3' ) , ToolKitError ( "ToolKit '%s' not supported!" % ( name ) ) elif name . startswith ( 'tk' ) : family = 'tk' assert name in ( 'tk' , ) , ToolKitError ( "ToolKit '%s' not supported!" % ( name ) ) elif name . startswith ( 'pg' ) : family = 'pg' assert name in ( 'pg' , ) , ToolKitError ( "ToolKit '%s' not supported!" % ( name ) ) else : ToolKitError ( "ToolKit '%s' not supported!" % ( name ) ) toolkit = name | Set the name of the GUI toolkit we should use . | 345 | 12 |
24,909 | def share_settings ( self , other , keylist = None , include_callbacks = True , callback = True ) : if keylist is None : keylist = self . group . keys ( ) if include_callbacks : for key in keylist : oset , mset = other . group [ key ] , self . group [ key ] other . group [ key ] = mset oset . merge_callbacks_to ( mset ) if callback : # make callbacks only after all items are set in the group # TODO: only make callbacks for values that changed? for key in keylist : other . group [ key ] . make_callback ( 'set' , other . group [ key ] . value ) | Sharing settings with other | 154 | 5 |
24,910 | def use ( wcspkg , raise_err = True ) : global coord_types , wcs_configured , WCS if wcspkg not in common . custom_wcs : # Try to dynamically load WCS modname = 'wcs_%s' % ( wcspkg ) path = os . path . join ( wcs_home , '%s.py' % ( modname ) ) try : my_import ( modname , path ) except ImportError : return False if wcspkg in common . custom_wcs : bnch = common . custom_wcs [ wcspkg ] WCS = bnch . wrapper_class coord_types = bnch . coord_types wcs_configured = True return True return False | Choose WCS package . | 162 | 4 |
24,911 | def _set_combobox ( self , attrname , vals , default = 0 ) : combobox = getattr ( self . w , attrname ) for val in vals : combobox . append_text ( val ) if default > len ( vals ) : default = 0 val = vals [ default ] combobox . show_text ( val ) return val | Populate combobox with given list . | 84 | 9 |
24,912 | def clear_data ( self ) : self . tab = None self . cols = [ ] self . _idx = [ ] self . x_col = '' self . y_col = '' self . w . xcombo . clear ( ) self . w . ycombo . clear ( ) self . w . x_lo . set_text ( '' ) self . w . x_hi . set_text ( '' ) self . w . y_lo . set_text ( '' ) self . w . y_hi . set_text ( '' ) | Clear comboboxes and columns . | 120 | 8 |
24,913 | def clear_plot ( self ) : self . tab_plot . clear ( ) self . tab_plot . draw ( ) self . save_plot . set_enabled ( False ) | Clear plot display . | 38 | 4 |
24,914 | def plot_two_columns ( self , reset_xlimits = False , reset_ylimits = False ) : self . clear_plot ( ) if self . tab is None : # No table data to plot return plt_kw = { 'lw' : self . settings . get ( 'linewidth' , 1 ) , 'ls' : self . settings . get ( 'linestyle' , '-' ) , 'color' : self . settings . get ( 'linecolor' , 'blue' ) , 'ms' : self . settings . get ( 'markersize' , 6 ) , 'mew' : self . settings . get ( 'markerwidth' , 0.5 ) , 'mfc' : self . settings . get ( 'markercolor' , 'red' ) } plt_kw [ 'mec' ] = plt_kw [ 'mfc' ] try : x_data , y_data , marker = self . _get_plot_data ( ) self . tab_plot . plot ( x_data , y_data , xtitle = self . _get_label ( 'x' ) , ytitle = self . _get_label ( 'y' ) , marker = marker , * * plt_kw ) if reset_xlimits : self . set_ylim_cb ( ) self . set_xlimits_widgets ( ) if reset_ylimits : self . set_xlim_cb ( ) self . set_ylimits_widgets ( ) if not ( reset_xlimits or reset_ylimits ) : self . set_xlim_cb ( redraw = False ) self . set_ylim_cb ( ) except Exception as e : self . logger . error ( str ( e ) ) else : self . save_plot . set_enabled ( True ) | Simple line plot for two selected columns . | 397 | 8 |
24,915 | def _get_plot_data ( self ) : _marker_type = self . settings . get ( 'markerstyle' , 'o' ) if self . x_col == self . _idxname : x_data = self . _idx else : x_data = self . tab [ self . x_col ] . data if self . y_col == self . _idxname : y_data = self . _idx else : y_data = self . tab [ self . y_col ] . data if self . tab . masked : if self . x_col == self . _idxname : x_mask = np . ones_like ( self . _idx , dtype = np . bool ) else : x_mask = ~ self . tab [ self . x_col ] . mask if self . y_col == self . _idxname : y_mask = np . ones_like ( self . _idx , dtype = np . bool ) else : y_mask = ~ self . tab [ self . y_col ] . mask mask = x_mask & y_mask x_data = x_data [ mask ] y_data = y_data [ mask ] if len ( x_data ) > 1 : i = np . argsort ( x_data ) # Sort X-axis to avoid messy line plot x_data = x_data [ i ] y_data = y_data [ i ] if not self . w . show_marker . get_state ( ) : _marker_type = None return x_data , y_data , _marker_type | Extract only good data point for plotting . | 352 | 9 |
24,916 | def _get_label ( self , axis ) : if axis == 'x' : colname = self . x_col else : # y colname = self . y_col if colname == self . _idxname : label = 'Index' else : col = self . tab [ colname ] if col . unit : label = '{0} ({1})' . format ( col . name , col . unit ) else : label = col . name return label | Return plot label for column for the given axis . | 100 | 10 |
24,917 | def x_select_cb ( self , w , index ) : try : self . x_col = self . cols [ index ] except IndexError as e : self . logger . error ( str ( e ) ) else : self . plot_two_columns ( reset_xlimits = True ) | Callback to set X - axis column . | 64 | 8 |
24,918 | def y_select_cb ( self , w , index ) : try : self . y_col = self . cols [ index ] except IndexError as e : self . logger . error ( str ( e ) ) else : self . plot_two_columns ( reset_ylimits = True ) | Callback to set Y - axis column . | 64 | 8 |
24,919 | def save_cb ( self ) : # This just defines the basename. # Extension has to be explicitly defined or things can get messy. w = Widgets . SaveDialog ( title = 'Save plot' ) target = w . get_path ( ) if target is None : # Save canceled return plot_ext = self . settings . get ( 'file_suffix' , '.png' ) if not target . endswith ( plot_ext ) : target += plot_ext # TODO: This can be a user preference? fig_dpi = 100 try : fig = self . tab_plot . get_figure ( ) fig . savefig ( target , dpi = fig_dpi ) except Exception as e : self . logger . error ( str ( e ) ) else : self . logger . info ( 'Table plot saved as {0}' . format ( target ) ) | Save plot to file . | 187 | 5 |
24,920 | def convert ( filepath , outfilepath ) : logger = logging . getLogger ( "example1" ) logger . setLevel ( logging . INFO ) fmt = logging . Formatter ( STD_FORMAT ) stderrHdlr = logging . StreamHandler ( ) stderrHdlr . setFormatter ( fmt ) logger . addHandler ( stderrHdlr ) fi = ImageViewCairo ( logger ) fi . configure ( 500 , 1000 ) # Load fits file image = load_data ( filepath , logger = logger ) # Make any adjustments to the image that we want fi . set_bg ( 1.0 , 1.0 , 1.0 ) fi . set_image ( image ) fi . auto_levels ( ) fi . zoom_fit ( ) fi . center_image ( ) ht_pts = 11.0 / point_in wd_pts = 8.5 / point_in off_x , off_y = 0 , 0 out_f = open ( outfilepath , 'w' ) surface = cairo . PDFSurface ( out_f , wd_pts , ht_pts ) # set pixels per inch surface . set_fallback_resolution ( 300 , 300 ) surface . set_device_offset ( off_x , off_y ) try : fi . save_image_as_surface ( surface ) surface . show_page ( ) surface . flush ( ) surface . finish ( ) finally : out_f . close ( ) | Convert FITS image to PDF . | 324 | 8 |
24,921 | def redo ( self ) : if not self . gui_up : return self . clear_mask ( ) image = self . fitsimage . get_image ( ) if image is None : return n_obj = len ( self . _maskobjs ) self . logger . debug ( 'Displaying {0} masks' . format ( n_obj ) ) if n_obj == 0 : return # Display info table self . recreate_toc ( ) # Draw on canvas self . masktag = self . canvas . add ( self . dc . CompoundObject ( * self . _maskobjs ) ) self . fitsimage . redraw ( ) | Image or masks have changed . Clear and redraw . | 136 | 11 |
24,922 | def clear_mask ( self ) : if self . masktag : try : self . canvas . delete_object_by_tag ( self . masktag , redraw = False ) except Exception : pass if self . maskhltag : try : self . canvas . delete_object_by_tag ( self . maskhltag , redraw = False ) except Exception : pass self . treeview . clear ( ) # Clear table too self . fitsimage . redraw ( ) | Clear mask from image . This does not clear loaded masks from memory . | 101 | 14 |
24,923 | def load_file ( self , filename ) : if not os . path . isfile ( filename ) : return self . logger . info ( 'Loading mask image from {0}' . format ( filename ) ) try : # 0=False, everything else True dat = fits . getdata ( filename ) . astype ( np . bool ) except Exception as e : self . logger . error ( '{0}: {1}' . format ( e . __class__ . __name__ , str ( e ) ) ) return key = '{0},{1}' . format ( self . maskcolor , self . maskalpha ) if key in self . tree_dict : sub_dict = self . tree_dict [ key ] else : sub_dict = { } self . tree_dict [ key ] = sub_dict # Add to listing seqstr = '{0:04d}' . format ( self . _seqno ) # Prepend 0s for proper sort sub_dict [ seqstr ] = Bunch . Bunch ( ID = seqstr , MASKFILE = os . path . basename ( filename ) ) self . _treepaths . append ( ( key , seqstr ) ) self . _seqno += 1 # Create mask layer obj = self . dc . Image ( 0 , 0 , masktorgb ( dat , color = self . maskcolor , alpha = self . maskalpha ) ) self . _maskobjs . append ( obj ) self . redo ( ) | Load mask image . | 317 | 4 |
24,924 | def _rgbtomask ( self , obj ) : dat = obj . get_image ( ) . get_data ( ) # RGB arrays return dat . sum ( axis = 2 ) . astype ( np . bool ) | Convert RGB arrays from mask canvas object back to boolean mask . | 47 | 13 |
24,925 | def hl_table2canvas ( self , w , res_dict ) : objlist = [ ] # Remove existing highlight if self . maskhltag : try : self . canvas . delete_object_by_tag ( self . maskhltag , redraw = False ) except Exception : pass for sub_dict in res_dict . values ( ) : for seqno in sub_dict : mobj = self . _maskobjs [ int ( seqno ) - 1 ] dat = self . _rgbtomask ( mobj ) obj = self . dc . Image ( 0 , 0 , masktorgb ( dat , color = self . hlcolor , alpha = self . hlalpha ) ) objlist . append ( obj ) # Draw on canvas if len ( objlist ) > 0 : self . maskhltag = self . canvas . add ( self . dc . CompoundObject ( * objlist ) ) self . fitsimage . redraw ( ) | Highlight mask on canvas when user click on table . | 208 | 11 |
24,926 | def hl_canvas2table_box ( self , canvas , tag ) : self . treeview . clear_selection ( ) # Remove existing box cobj = canvas . get_object_by_tag ( tag ) if cobj . kind != 'rectangle' : return canvas . delete_object_by_tag ( tag , redraw = False ) # Remove existing highlight if self . maskhltag : try : canvas . delete_object_by_tag ( self . maskhltag , redraw = True ) except Exception : pass # Nothing to do if no masks are displayed try : obj = canvas . get_object_by_tag ( self . masktag ) except Exception : return if obj . kind != 'compound' : return # Nothing to do if table has no data if len ( self . _maskobjs ) == 0 : return # Find masks that intersect the rectangle for i , mobj in enumerate ( self . _maskobjs ) : # The actual mask mask1 = self . _rgbtomask ( mobj ) # The selected area rgbimage = mobj . get_image ( ) mask2 = rgbimage . get_shape_mask ( cobj ) # Highlight mask with intersect if np . any ( mask1 & mask2 ) : self . _highlight_path ( self . _treepaths [ i ] ) | Highlight all masks inside user drawn box on table . | 290 | 11 |
24,927 | def hl_canvas2table ( self , canvas , button , data_x , data_y ) : self . treeview . clear_selection ( ) # Remove existing highlight if self . maskhltag : try : canvas . delete_object_by_tag ( self . maskhltag , redraw = True ) except Exception : pass # Nothing to do if no masks are displayed try : obj = canvas . get_object_by_tag ( self . masktag ) except Exception : return if obj . kind != 'compound' : return # Nothing to do if table has no data if len ( self . _maskobjs ) == 0 : return for i , mobj in enumerate ( self . _maskobjs ) : mask1 = self . _rgbtomask ( mobj ) # Highlight mask covering selected cursor position if mask1 [ int ( data_y ) , int ( data_x ) ] : self . _highlight_path ( self . _treepaths [ i ] ) | Highlight mask on table when user click on canvas . | 216 | 11 |
24,928 | def contains_pt ( self , pt ) : obj1 , obj2 = self . objects return obj2 . contains_pt ( pt ) and np . logical_not ( obj1 . contains_pt ( pt ) ) | Containment test . | 46 | 4 |
24,929 | def contains_pts ( self , pts ) : obj1 , obj2 = self . objects arg1 = obj2 . contains_pts ( pts ) arg2 = np . logical_not ( obj1 . contains_pts ( pts ) ) return np . logical_and ( arg1 , arg2 ) | Containment test on arrays . | 66 | 6 |
24,930 | def register_wcs ( name , wrapper_class , coord_types ) : global custom_wcs custom_wcs [ name ] = Bunch . Bunch ( name = name , wrapper_class = wrapper_class , coord_types = coord_types ) | Register a custom WCS wrapper . | 53 | 6 |
24,931 | def choose_coord_units ( header ) : cunit = header [ 'CUNIT1' ] match = re . match ( r'^deg\s*$' , cunit ) if match : return 'degree' # raise WCSError("Don't understand units '%s'" % (cunit)) return 'degree' | Return the appropriate key code for the units value for the axes by examining the FITS header . | 72 | 19 |
24,932 | def get_coord_system_name ( header ) : try : ctype = header [ 'CTYPE1' ] . strip ( ) . upper ( ) except KeyError : try : # see if we have an "RA" header ra = header [ 'RA' ] # noqa try : equinox = float ( header [ 'EQUINOX' ] ) if equinox < 1984.0 : radecsys = 'FK4' else : radecsys = 'FK5' except KeyError : radecsys = 'ICRS' return radecsys . lower ( ) except KeyError : return 'raw' match = re . match ( r'^GLON\-.*$' , ctype ) if match : return 'galactic' match = re . match ( r'^ELON\-.*$' , ctype ) if match : return 'ecliptic' match = re . match ( r'^RA\-\-\-.*$' , ctype ) if match : hdkey = 'RADECSYS' try : radecsys = header [ hdkey ] except KeyError : try : hdkey = 'RADESYS' radecsys = header [ hdkey ] except KeyError : # missing keyword # RADESYS defaults to IRCS unless EQUINOX is given # alone, in which case it defaults to FK4 prior to 1984 # and FK5 after 1984. try : equinox = float ( header [ 'EQUINOX' ] ) if equinox < 1984.0 : radecsys = 'FK4' else : radecsys = 'FK5' except KeyError : radecsys = 'ICRS' radecsys = radecsys . strip ( ) return radecsys . lower ( ) match = re . match ( r'^HPLN\-.*$' , ctype ) if match : return 'helioprojective' match = re . match ( r'^HGLT\-.*$' , ctype ) if match : return 'heliographicstonyhurst' match = re . match ( r'^PIXEL$' , ctype ) if match : return 'pixel' match = re . match ( r'^LINEAR$' , ctype ) if match : return 'pixel' #raise WCSError("Cannot determine appropriate coordinate system from FITS header") # noqa return 'icrs' | Return an appropriate key code for the axes coordinate system by examining the FITS header . | 532 | 17 |
24,933 | def datapt_to_wcspt ( self , datapt , coords = 'data' , naxispath = None ) : # We provide a list comprehension version for WCS packages that # don't support array operations. if naxispath : raise NotImplementedError return np . asarray ( [ self . pixtoradec ( ( pt [ 0 ] , pt [ 1 ] ) , coords = coords ) for pt in datapt ] ) | Convert multiple data points to WCS . | 97 | 8 |
24,934 | def wcspt_to_datapt ( self , wcspt , coords = 'data' , naxispath = None ) : # We provide a list comprehension version for WCS packages that # don't support array operations. if naxispath : raise NotImplementedError return np . asarray ( [ self . radectopix ( pt [ 0 ] , pt [ 1 ] , coords = coords ) for pt in wcspt ] ) | Convert multiple WCS to data points . | 97 | 8 |
24,935 | def fix_bad_headers ( self ) : # WCSLIB doesn't like "nonstandard" units unit = self . header . get ( 'CUNIT1' , 'deg' ) if unit . upper ( ) == 'DEGREE' : # self.header.update('CUNIT1', 'deg') self . header [ 'CUNIT1' ] = 'deg' unit = self . header . get ( 'CUNIT2' , 'deg' ) if unit . upper ( ) == 'DEGREE' : # self.header.update('CUNIT2', 'deg') self . header [ 'CUNIT2' ] = 'deg' | Fix up bad headers that cause problems for the wrapped WCS module . | 145 | 13 |
24,936 | def fov_for_height_and_distance ( height , distance ) : vfov_deg = np . degrees ( 2.0 * np . arctan ( height * 0.5 / distance ) ) return vfov_deg | Calculate the FOV needed to get a given frustum height at a given distance . | 52 | 19 |
24,937 | def set_gl_transform ( self ) : tangent = np . tan ( self . fov_deg / 2.0 / 180.0 * np . pi ) vport_radius = self . near_plane * tangent # calculate aspect of the viewport if self . vport_wd_px < self . vport_ht_px : vport_wd = 2.0 * vport_radius vport_ht = vport_wd * self . vport_ht_px / float ( self . vport_wd_px ) else : vport_ht = 2.0 * vport_radius vport_wd = vport_ht * self . vport_wd_px / float ( self . vport_ht_px ) gl . glFrustum ( - 0.5 * vport_wd , 0.5 * vport_wd , # left, right - 0.5 * vport_ht , 0.5 * vport_ht , # bottom, top self . near_plane , self . far_plane ) M = Matrix4x4 . look_at ( self . position , self . target , self . up , False ) gl . glMultMatrixf ( M . get ( ) ) | This side effects the OpenGL context to set the view to match the camera . | 266 | 15 |
24,938 | def get_translation_speed ( self , distance_from_target ) : return ( distance_from_target * np . tan ( self . fov_deg / 2.0 / 180.0 * np . pi ) ) | Returns the translation speed for distance_from_target in units per radius . | 48 | 15 |
24,939 | def orbit ( self , x1_px , y1_px , x2_px , y2_px ) : px_per_deg = self . vport_radius_px / float ( self . orbit_speed ) radians_per_px = 1.0 / px_per_deg * np . pi / 180.0 t2p = self . position - self . target M = Matrix4x4 . rotation_around_origin ( ( x1_px - x2_px ) * radians_per_px , self . ground ) t2p = M * t2p self . up = M * self . up right = ( self . up ^ t2p ) . normalized ( ) M = Matrix4x4 . rotation_around_origin ( ( y1_px - y2_px ) * radians_per_px , right ) t2p = M * t2p self . up = M * self . up self . position = self . target + t2p | Causes the camera to orbit around the target point . This is also called tumbling in some software packages . | 218 | 22 |
24,940 | def track ( self , delta_pixels , push_target = False , adj_fov = False ) : direction = self . target - self . position distance_from_target = direction . length ( ) direction = direction . normalized ( ) initial_ht = frustum_height_at_distance ( self . fov_deg , distance_from_target ) ## print("frustum height at distance %.4f is %.4f" % ( ## distance_from_target, initial_ht)) speed_per_radius = self . get_translation_speed ( distance_from_target ) px_per_unit = self . vport_radius_px / speed_per_radius dolly_distance = delta_pixels / px_per_unit if not push_target : distance_from_target -= dolly_distance if distance_from_target < self . push_threshold * self . near_plane : distance_from_target = self . push_threshold * self . near_plane self . position += direction * dolly_distance self . target = self . position + direction * distance_from_target if adj_fov : # adjust FOV to match the size of the target before the dolly direction = self . target - self . position distance_from_target = direction . length ( ) fov_deg = fov_for_height_and_distance ( initial_ht , distance_from_target ) #print("fov is now %.4f" % fov_deg) self . fov_deg = fov_deg | This causes the camera to translate forward into the scene . This is also called dollying or tracking in some software packages . Passing in a negative delta causes the opposite motion . | 341 | 34 |
24,941 | def get_wireframe ( viewer , x , y , z , * * kwargs ) : # TODO: something like this would make a great utility function # for ginga n , m = x . shape objs = [ ] for i in range ( n ) : pts = np . asarray ( [ ( x [ i ] [ j ] , y [ i ] [ j ] , z [ i ] [ j ] ) for j in range ( m ) ] ) objs . append ( viewer . dc . Path ( pts , * * kwargs ) ) for j in range ( m ) : pts = np . asarray ( [ ( x [ i ] [ j ] , y [ i ] [ j ] , z [ i ] [ j ] ) for i in range ( n ) ] ) objs . append ( viewer . dc . Path ( pts , * * kwargs ) ) return viewer . dc . CompoundObject ( * objs ) | Produce a compound object of paths implementing a wireframe . x y z are expected to be 2D arrays of points making up the mesh . | 204 | 29 |
24,942 | def get_fileinfo ( filespec , cache_dir = None ) : if cache_dir is None : cache_dir = tempfile . gettempdir ( ) # Loads first science extension by default. # This prevents [None] to be loaded instead. idx = None name_ext = '' # User specified an index using bracket notation at end of path? match = re . match ( r'^(.+)\[(.+)\]$' , filespec ) if match : filespec = match . group ( 1 ) idx = match . group ( 2 ) if ',' in idx : hduname , extver = idx . split ( ',' ) hduname = hduname . strip ( ) if re . match ( r'^\d+$' , extver ) : extver = int ( extver ) idx = ( hduname , extver ) name_ext = "[%s,%d]" % idx else : idx = idx . strip ( ) name_ext = "[%s]" % idx else : if re . match ( r'^\d+$' , idx ) : idx = int ( idx ) name_ext = "[%d]" % idx else : idx = idx . strip ( ) name_ext = "[%s]" % idx else : filespec = filespec url = filespec filepath = None # Does this look like a URL? match = re . match ( r"^(\w+)://(.+)$" , filespec ) if match : urlinfo = urllib . parse . urlparse ( filespec ) if urlinfo . scheme == 'file' : # local file filepath = str ( pathlib . Path ( urlinfo . path ) ) else : path , filename = os . path . split ( urlinfo . path ) filepath = get_download_path ( url , filename , cache_dir ) else : # Not a URL filepath = filespec url = pathlib . Path ( os . path . abspath ( filepath ) ) . as_uri ( ) ondisk = os . path . exists ( filepath ) dirname , fname = os . path . split ( filepath ) fname_pfx , fname_sfx = os . path . splitext ( fname ) name = fname_pfx + name_ext res = Bunch . Bunch ( filepath = filepath , url = url , numhdu = idx , name = name , idx = name_ext , ondisk = ondisk ) return res | Parse a file specification and return information about it . | 564 | 11 |
24,943 | def shorten_name ( name , char_limit , side = 'right' ) : # TODO: A more elegant way to do this? if char_limit is not None and len ( name ) > char_limit : info = get_fileinfo ( name ) if info . numhdu is not None : i = name . rindex ( '[' ) s = ( name [ : i ] , name [ i : ] ) len_sfx = len ( s [ 1 ] ) len_pfx = char_limit - len_sfx - 4 + 1 if len_pfx > 0 : if side == 'right' : name = '{0}...{1}' . format ( s [ 0 ] [ : len_pfx ] , s [ 1 ] ) elif side == 'left' : name = '...{0}{1}' . format ( s [ 0 ] [ - len_pfx : ] , s [ 1 ] ) else : name = '...{0}' . format ( s [ 1 ] ) else : len1 = char_limit - 3 + 1 if side == 'right' : name = '{0}...' . format ( name [ : len1 ] ) elif side == 'left' : name = '...{0}' . format ( name [ - len1 : ] ) return name | Shorten name if it is longer than char_limit . If side == right then the right side of the name is shortened ; if left then the left side is shortened . In either case the suffix of the name is preserved . | 289 | 46 |
24,944 | def update_params ( self , param_d ) : for param in self . paramlst : if param . name in param_d : value = param_d [ param . name ] setattr ( self . obj , param . name , value ) | Update the attributes in self . obj that match the keys in param_d . | 53 | 16 |
24,945 | def hue_sat_to_cmap ( hue , sat ) : import colorsys # normalize to floats hue = float ( hue ) / 360.0 sat = float ( sat ) / 100.0 res = [ ] for val in range ( 256 ) : hsv_val = float ( val ) / 255.0 r , g , b = colorsys . hsv_to_rgb ( hue , sat , hsv_val ) res . append ( ( r , g , b ) ) return res | Mkae a color map from a hue and saturation value . | 108 | 13 |
24,946 | def setitem ( self , key , value ) : with self . lock : self . tbl [ key ] = value | Maps dictionary keys to values for assignment . Called for dictionary style access with assignment . | 25 | 16 |
24,947 | def get ( self , key , alt = None ) : with self . lock : if key in self : return self . getitem ( key ) else : return alt | If dictionary contains _key_ return the associated value otherwise return _alt_ . | 34 | 16 |
24,948 | def setdefault ( self , key , value ) : with self . lock : if key in self : return self . getitem ( key ) else : self . setitem ( key , value ) return value | Atomic store conditional . Stores _value_ into dictionary at _key_ but only if _key_ does not already exist in the dictionary . Returns the old value found or the new value . | 42 | 39 |
24,949 | def help ( self ) : if not self . fv . gpmon . has_plugin ( 'WBrowser' ) : self . _help_docstring ( ) return self . fv . start_global_plugin ( 'WBrowser' ) # need to let GUI finish processing, it seems self . fv . update_pending ( ) obj = self . fv . gpmon . get_plugin ( 'WBrowser' ) obj . show_help ( plugin = self , no_url_callback = self . _help_docstring ) | Display help for the plugin . | 116 | 6 |
24,950 | def modes_off ( self ) : bm = self . fitsimage . get_bindmap ( ) bm . reset_mode ( self . fitsimage ) | Turn off any mode user may be in . | 34 | 9 |
24,951 | def load_np ( self , imname , data_np , imtype , header ) : # future: handle imtype load_buffer = self . _client . lookup_attr ( 'load_buffer' ) return load_buffer ( imname , self . _chname , Blob ( data_np . tobytes ( ) ) , data_np . shape , str ( data_np . dtype ) , header , { } , False ) | Display a numpy image buffer in a remote Ginga reference viewer . | 95 | 14 |
24,952 | def load_hdu ( self , imname , hdulist , num_hdu ) : buf_io = BytesIO ( ) hdulist . writeto ( buf_io ) load_fits_buffer = self . _client . lookup_attr ( 'load_fits_buffer' ) return load_fits_buffer ( imname , self . _chname , Blob ( buf_io . getvalue ( ) ) , num_hdu , { } ) | Display an astropy . io . fits HDU in a remote Ginga reference viewer . | 103 | 18 |
24,953 | def load_fitsbuf ( self , imname , fitsbuf , num_hdu ) : load_fits_buffer = self . _client_ . lookup_attr ( 'load_fits_buffer' ) return load_fits_buffer ( imname , self . _chname , Blob ( fitsbuf ) , num_hdu , { } ) | Display a FITS file buffer in a remote Ginga reference viewer . | 75 | 14 |
24,954 | def set_widget ( self , canvas ) : self . tkcanvas = canvas canvas . bind ( "<Configure>" , self . _resize_cb ) width = canvas . winfo_width ( ) height = canvas . winfo_height ( ) # see reschedule_redraw() method self . _defer_task = TkHelp . Timer ( tkcanvas = canvas ) self . _defer_task . add_callback ( 'expired' , lambda timer : self . delayed_redraw ( ) ) self . msgtask = TkHelp . Timer ( tkcanvas = canvas ) self . msgtask . add_callback ( 'expired' , lambda timer : self . onscreen_message ( None ) ) self . configure_window ( width , height ) | Call this method with the Tkinter canvas that will be used for the display . | 174 | 17 |
24,955 | def _set_lim_and_transforms ( self ) : # There are three important coordinate spaces going on here: # # 1. Data space: The space of the data itself # # 2. Axes space: The unit rectangle (0, 0) to (1, 1) # covering the entire plot area. # # 3. Display space: The coordinates of the resulting image, # often in pixels or dpi/inch. # This function makes heavy use of the Transform classes in # ``lib/matplotlib/transforms.py.`` For more information, see # the inline documentation there. # The goal of the first two transformations is to get from the # data space to axes space. It is separated into a non-affine # and affine part so that the non-affine part does not have to be # recomputed when a simple affine change to the figure has been # made (such as resizing the window or changing the dpi). # 3) This is the transformation from axes space to display # space. self . transAxes = BboxTransformTo ( self . bbox ) # Now put these 3 transforms together -- from data all the way # to display coordinates. Using the '+' operator, these # transforms will be applied "in order". The transforms are # automatically simplified, if possible, by the underlying # transformation framework. #self.transData = \ # self.transProjection + self.transAffine + self.transAxes self . transData = self . GingaTransform ( ) self . transData . viewer = self . viewer # self._xaxis_transform = blended_transform_factory( # self.transData, self.transAxes) # self._yaxis_transform = blended_transform_factory( # self.transAxes, self.transData) self . _xaxis_transform = self . transData self . _yaxis_transform = self . transData | This is called once when the plot is created to set up all the transforms for the data text and grids . | 412 | 22 |
24,956 | def start_pan ( self , x , y , button ) : bd = self . viewer . get_bindings ( ) data_x , data_y = self . viewer . get_data_xy ( x , y ) event = PointEvent ( button = button , state = 'down' , data_x = data_x , data_y = data_y , viewer = self . viewer ) if button == 1 : bd . ms_pan ( self . viewer , event , data_x , data_y ) elif button == 3 : bd . ms_zoom ( self . viewer , event , data_x , data_y ) | Called when a pan operation has started . | 140 | 9 |
24,957 | def get_surface_as_bytes ( self , order = None ) : arr8 = self . get_surface_as_array ( order = order ) return arr8 . tobytes ( order = 'C' ) | Returns the surface area as a bytes encoded RGB image buffer . Subclass should override if there is a more efficient conversion than from generating a numpy array first . | 46 | 32 |
24,958 | def reorder ( self , dst_order , arr , src_order = None ) : if dst_order is None : dst_order = self . viewer . rgb_order if src_order is None : src_order = self . rgb_order if src_order != dst_order : arr = trcalc . reorder_image ( dst_order , arr , src_order ) return arr | Reorder the output array to match that needed by the viewer . | 85 | 13 |
24,959 | def add_cmap ( name , clst ) : global cmaps assert len ( clst ) == min_cmap_len , ValueError ( "color map '%s' length mismatch %d != %d (needed)" % ( name , len ( clst ) , min_cmap_len ) ) cmaps [ name ] = ColorMap ( name , clst ) | Add a color map . | 81 | 5 |
24,960 | def get_names ( ) : res = list ( cmaps . keys ( ) ) res = sorted ( res , key = lambda s : s . lower ( ) ) return res | Get colormap names . | 37 | 6 |
24,961 | def matplotlib_to_ginga_cmap ( cm , name = None ) : if name is None : name = cm . name arr = cm ( np . arange ( 0 , min_cmap_len ) / np . float ( min_cmap_len - 1 ) ) clst = arr [ : , 0 : 3 ] return ColorMap ( name , clst ) | Convert matplotlib colormap to Ginga s . | 83 | 13 |
24,962 | def ginga_to_matplotlib_cmap ( cm , name = None ) : if name is None : name = cm . name from matplotlib . colors import ListedColormap carr = np . asarray ( cm . clst ) mpl_cm = ListedColormap ( carr , name = name , N = len ( carr ) ) return mpl_cm | Convert Ginga colormap to matplotlib s . | 87 | 13 |
24,963 | def add_matplotlib_cmap ( cm , name = None ) : global cmaps cmap = matplotlib_to_ginga_cmap ( cm , name = name ) cmaps [ cmap . name ] = cmap | Add a matplotlib colormap . | 52 | 9 |
24,964 | def add_matplotlib_cmaps ( fail_on_import_error = True ) : try : from matplotlib import cm as _cm from matplotlib . cbook import mplDeprecation except ImportError : if fail_on_import_error : raise # silently fail return for name in _cm . cmap_d : if not isinstance ( name , str ) : continue try : # Do not load deprecated colormaps with warnings . catch_warnings ( ) : warnings . simplefilter ( 'error' , mplDeprecation ) cm = _cm . get_cmap ( name ) add_matplotlib_cmap ( cm , name = name ) except Exception as e : if fail_on_import_error : print ( "Error adding colormap '%s': %s" % ( name , str ( e ) ) ) | Add all matplotlib colormaps . | 186 | 9 |
24,965 | def add_legend ( self ) : cuts = [ tag for tag in self . tags if tag is not self . _new_cut ] self . cuts_plot . ax . legend ( cuts , loc = 'best' , shadow = True , fancybox = True , prop = { 'size' : 8 } , labelspacing = 0.2 ) | Add or update Cuts plot legend . | 75 | 8 |
24,966 | def cut_at ( self , cuttype ) : data_x , data_y = self . fitsimage . get_last_data_xy ( ) image = self . fitsimage . get_image ( ) wd , ht = image . get_size ( ) coords = [ ] if cuttype == 'horizontal' : coords . append ( ( 0 , data_y , wd , data_y ) ) elif cuttype == 'vertical' : coords . append ( ( data_x , 0 , data_x , ht ) ) count = self . _get_cut_index ( ) tag = "cuts%d" % ( count ) cuts = [ ] for ( x1 , y1 , x2 , y2 ) in coords : # calculate center of line wd = x2 - x1 dw = wd // 2 ht = y2 - y1 dh = ht // 2 x , y = x1 + dw + 4 , y1 + dh + 4 cut = self . _create_cut ( x , y , count , x1 , y1 , x2 , y2 , color = 'cyan' ) self . _update_tines ( cut ) cuts . append ( cut ) if len ( cuts ) == 1 : cut = cuts [ 0 ] else : cut = self . _combine_cuts ( * cuts ) cut . set_data ( count = count ) self . canvas . delete_object_by_tag ( tag ) self . canvas . add ( cut , tag = tag ) self . add_cuts_tag ( tag ) self . logger . debug ( "redoing cut plots" ) return self . replot_all ( ) | Perform a cut at the last mouse position in the image . cuttype determines the type of cut made . | 364 | 22 |
24,967 | def width_radius_changed_cb ( self , widget , val ) : self . width_radius = val self . redraw_cuts ( ) self . replot_all ( ) return True | Callback executed when the Width radius is changed . | 41 | 9 |
24,968 | def save_cb ( self , mode ) : # This just defines the basename. # Extension has to be explicitly defined or things can get messy. w = Widgets . SaveDialog ( title = 'Save {0} data' . format ( mode ) ) filename = w . get_path ( ) if filename is None : # user canceled dialog return # TODO: This can be a user preference? fig_dpi = 100 if mode == 'cuts' : fig , xarr , yarr = self . cuts_plot . get_data ( ) elif mode == 'slit' : fig , xarr , yarr = self . slit_plot . get_data ( ) figname = filename + '.png' self . logger . info ( "saving figure as: %s" % ( figname ) ) fig . savefig ( figname , dpi = fig_dpi ) dataname = filename + '.npz' self . logger . info ( "saving data as: %s" % ( dataname ) ) np . savez_compressed ( dataname , x = xarr , y = yarr ) | Save image figure and plot data arrays . | 244 | 8 |
24,969 | def zoom_cb ( self , fitsimage , event ) : chviewer = self . fv . getfocus_viewer ( ) bd = chviewer . get_bindings ( ) if hasattr ( bd , 'sc_zoom' ) : return bd . sc_zoom ( chviewer , event ) return False | Zoom event in the pan window . Just zoom the channel viewer . | 74 | 14 |
24,970 | def zoom_pinch_cb ( self , fitsimage , event ) : chviewer = self . fv . getfocus_viewer ( ) bd = chviewer . get_bindings ( ) if hasattr ( bd , 'pi_zoom' ) : return bd . pi_zoom ( chviewer , event ) return False | Pinch event in the pan window . Just zoom the channel viewer . | 77 | 14 |
24,971 | def pan_pan_cb ( self , fitsimage , event ) : chviewer = self . fv . getfocus_viewer ( ) bd = chviewer . get_bindings ( ) if hasattr ( bd , 'pa_pan' ) : return bd . pa_pan ( chviewer , event ) return False | Pan event in the pan window . Just pan the channel viewer . | 74 | 13 |
24,972 | def set_widget ( self , canvas_w ) : self . logger . debug ( "set widget canvas_w=%s" % canvas_w ) self . pgcanvas = canvas_w | Call this method with the widget that will be used for the display . | 42 | 14 |
24,973 | def run ( self ) : os . system ( "cp python-bugzilla.spec /tmp" ) try : os . system ( "rm -rf python-bugzilla-%s" % get_version ( ) ) self . run_command ( 'sdist' ) os . system ( 'rpmbuild -ta --clean dist/python-bugzilla-%s.tar.gz' % get_version ( ) ) finally : os . system ( "mv /tmp/python-bugzilla.spec ." ) | Run sdist then rpmbuild the tar . gz | 112 | 13 |
24,974 | def parse_response ( self , response ) : parser , unmarshaller = self . getparser ( ) parser . feed ( response . text . encode ( 'utf-8' ) ) parser . close ( ) return unmarshaller . close ( ) | Parse XMLRPC response | 54 | 6 |
24,975 | def _request_helper ( self , url , request_body ) : response = None # pylint: disable=try-except-raise try : response = self . session . post ( url , data = request_body , * * self . request_defaults ) # We expect utf-8 from the server response . encoding = 'UTF-8' # update/set any cookies if self . _cookiejar is not None : for cookie in response . cookies : self . _cookiejar . set_cookie ( cookie ) if self . _cookiejar . filename is not None : # Save is required only if we have a filename self . _cookiejar . save ( ) response . raise_for_status ( ) return self . parse_response ( response ) except requests . RequestException as e : if not response : raise raise ProtocolError ( url , response . status_code , str ( e ) , response . headers ) except Fault : raise except Exception : e = BugzillaError ( str ( sys . exc_info ( ) [ 1 ] ) ) # pylint: disable=attribute-defined-outside-init e . __traceback__ = sys . exc_info ( ) [ 2 ] # pylint: enable=attribute-defined-outside-init raise e | A helper method to assist in making a request and provide a parsed response . | 269 | 15 |
24,976 | def open_without_clobber ( name , * args ) : fd = None count = 1 orig_name = name while fd is None : try : fd = os . open ( name , os . O_CREAT | os . O_EXCL , 0o666 ) except OSError as err : if err . errno == errno . EEXIST : name = "%s.%i" % ( orig_name , count ) count += 1 else : raise IOError ( err . errno , err . strerror , err . filename ) fobj = open ( name , * args ) if fd != fobj . fileno ( ) : os . close ( fd ) return fobj | Try to open the given file with the given mode ; if that filename exists try name . 1 name . 2 etc . until we find an unused filename . | 155 | 31 |
24,977 | def _do_info ( bz , opt ) : # All these commands call getproducts internally, so do it up front # with minimal include_fields for speed def _filter_components ( compdetails ) : ret = { } for k , v in compdetails . items ( ) : if v . get ( "is_active" , True ) : ret [ k ] = v return ret productname = ( opt . components or opt . component_owners or opt . versions ) include_fields = [ "name" , "id" ] fastcomponents = ( opt . components and not opt . active_components ) if opt . versions : include_fields += [ "versions" ] if opt . component_owners : include_fields += [ "components.default_assigned_to" , "components.name" , ] if ( opt . active_components and any ( [ "components" in i for i in include_fields ] ) ) : include_fields += [ "components.is_active" ] bz . refresh_products ( names = productname and [ productname ] or None , include_fields = include_fields ) if opt . products : for name in sorted ( [ p [ "name" ] for p in bz . getproducts ( ) ] ) : print ( name ) elif fastcomponents : for name in sorted ( bz . getcomponents ( productname ) ) : print ( name ) elif opt . components : details = bz . getcomponentsdetails ( productname ) for name in sorted ( _filter_components ( details ) ) : print ( name ) elif opt . versions : proddict = bz . getproducts ( ) [ 0 ] for v in proddict [ 'versions' ] : print ( to_encoding ( v [ "name" ] ) ) elif opt . component_owners : details = bz . getcomponentsdetails ( productname ) for c in sorted ( _filter_components ( details ) ) : print ( to_encoding ( u"%s: %s" % ( c , details [ c ] [ 'default_assigned_to' ] ) ) ) | Handle the info subcommand | 464 | 5 |
24,978 | def _make_bz_instance ( opt ) : if opt . bztype != 'auto' : log . info ( "Explicit --bztype is no longer supported, ignoring" ) cookiefile = None tokenfile = None use_creds = False if opt . cache_credentials : cookiefile = opt . cookiefile or - 1 tokenfile = opt . tokenfile or - 1 use_creds = True bz = bugzilla . Bugzilla ( url = opt . bugzilla , cookiefile = cookiefile , tokenfile = tokenfile , sslverify = opt . sslverify , use_creds = use_creds , cert = opt . cert ) return bz | Build the Bugzilla instance we will use | 159 | 8 |
24,979 | def _handle_login ( opt , action , bz ) : is_login_command = ( action == 'login' ) do_interactive_login = ( is_login_command or opt . login or opt . username or opt . password ) username = getattr ( opt , "pos_username" , None ) or opt . username password = getattr ( opt , "pos_password" , None ) or opt . password try : if do_interactive_login : if bz . url : print ( "Logging into %s" % urlparse ( bz . url ) [ 1 ] ) bz . interactive_login ( username , password , restrict_login = opt . restrict_login ) except bugzilla . BugzillaError as e : print ( str ( e ) ) sys . exit ( 1 ) if opt . ensure_logged_in and not bz . logged_in : print ( "--ensure-logged-in passed but you aren't logged in to %s" % bz . url ) sys . exit ( 1 ) if is_login_command : msg = "Login successful." if bz . cookiefile or bz . tokenfile : msg = "Login successful, token cache updated." print ( msg ) sys . exit ( 0 ) | Handle all login related bits | 272 | 5 |
24,980 | def fix_url ( url ) : if '://' not in url : log . debug ( 'No scheme given for url, assuming https' ) url = 'https://' + url if url . count ( '/' ) < 3 : log . debug ( 'No path given for url, assuming /xmlrpc.cgi' ) url = url + '/xmlrpc.cgi' return url | Turn passed url into a bugzilla XMLRPC web url | 83 | 12 |
24,981 | def _init_class_from_url ( self ) : from bugzilla import RHBugzilla if isinstance ( self , RHBugzilla ) : return c = None if "bugzilla.redhat.com" in self . url : log . info ( "Using RHBugzilla for URL containing bugzilla.redhat.com" ) c = RHBugzilla else : try : extensions = self . _proxy . Bugzilla . extensions ( ) if "RedHat" in extensions . get ( 'extensions' , { } ) : log . info ( "Found RedHat bugzilla extension, " "using RHBugzilla" ) c = RHBugzilla except Fault : log . debug ( "Failed to fetch bugzilla extensions" , exc_info = True ) if not c : return self . __class__ = c | Detect if we should use RHBugzilla class and if so set it | 172 | 14 |
24,982 | def _login ( self , user , password , restrict_login = None ) : payload = { 'login' : user , 'password' : password } if restrict_login : payload [ 'restrict_login' ] = True return self . _proxy . User . login ( payload ) | Backend login method for Bugzilla3 | 60 | 8 |
24,983 | def login ( self , user = None , password = None , restrict_login = None ) : if self . api_key : raise ValueError ( "cannot login when using an API key" ) if user : self . user = user if password : self . password = password if not self . user : raise ValueError ( "missing username" ) if not self . password : raise ValueError ( "missing password" ) if restrict_login : log . info ( "logging in with restrict_login=True" ) try : ret = self . _login ( self . user , self . password , restrict_login ) self . password = '' log . info ( "login successful for user=%s" , self . user ) return ret except Fault as e : raise BugzillaError ( "Login failed: %s" % str ( e . faultString ) ) | Attempt to log in using the given username and password . Subsequent method calls will use this username and password . Returns False if login fails otherwise returns some kind of login info - typically either a numeric userid or a dict of user info . | 181 | 48 |
24,984 | def interactive_login ( self , user = None , password = None , force = False , restrict_login = None ) : ignore = force log . debug ( 'Calling interactive_login' ) if not user : sys . stdout . write ( 'Bugzilla Username: ' ) sys . stdout . flush ( ) user = sys . stdin . readline ( ) . strip ( ) if not password : password = getpass . getpass ( 'Bugzilla Password: ' ) log . info ( 'Logging in... ' ) self . login ( user , password , restrict_login ) log . info ( 'Authorization cookie received.' ) | Helper method to handle login for this bugzilla instance . | 134 | 11 |
24,985 | def logout ( self ) : self . _logout ( ) self . disconnect ( ) self . user = '' self . password = '' | Log out of bugzilla . Drops server connection and user info and destroys authentication cookies . | 29 | 17 |
24,986 | def logged_in ( self ) : try : self . _proxy . User . get ( { 'ids' : [ ] } ) return True except Fault as e : if e . faultCode == 505 or e . faultCode == 32000 : return False raise e | This is True if this instance is logged in else False . | 55 | 12 |
24,987 | def _getbugfields ( self ) : r = self . _proxy . Bug . fields ( { 'include_fields' : [ 'name' ] } ) return [ f [ 'name' ] for f in r [ 'fields' ] ] | Get the list of valid fields for Bug objects | 52 | 9 |
24,988 | def getbugfields ( self , force_refresh = False ) : if force_refresh or not self . _cache . bugfields : log . debug ( "Refreshing bugfields" ) self . _cache . bugfields = self . _getbugfields ( ) self . _cache . bugfields . sort ( ) log . debug ( "bugfields = %s" , self . _cache . bugfields ) return self . _cache . bugfields | Calls getBugFields which returns a list of fields in each bug for this bugzilla instance . This can be used to set the list of attrs on the Bug object . | 97 | 37 |
24,989 | def refresh_products ( self , * * kwargs ) : for product in self . product_get ( * * kwargs ) : updated = False for current in self . _cache . products [ : ] : if ( current . get ( "id" , - 1 ) != product . get ( "id" , - 2 ) and current . get ( "name" , - 1 ) != product . get ( "name" , - 2 ) ) : continue _nested_update ( current , product ) updated = True break if not updated : self . _cache . products . append ( product ) | Refresh a product s cached info . Basically calls product_get with the passed arguments and tries to intelligently update our product cache . | 127 | 27 |
24,990 | def getproducts ( self , force_refresh = False , * * kwargs ) : if force_refresh or not self . _cache . products : self . refresh_products ( * * kwargs ) return self . _cache . products | Query all products and return the raw dict info . Takes all the same arguments as product_get . | 53 | 20 |
24,991 | def getcomponentdetails ( self , product , component , force_refresh = False ) : d = self . getcomponentsdetails ( product , force_refresh ) return d [ component ] | Helper for accessing a single component s info . This is a wrapper around getcomponentsdetails see that for explanation | 40 | 22 |
24,992 | def getcomponents ( self , product , force_refresh = False ) : proddict = self . _lookup_product_in_cache ( product ) product_id = proddict . get ( "id" , None ) if ( force_refresh or product_id is None or product_id not in self . _cache . component_names ) : self . refresh_products ( names = [ product ] , include_fields = [ "name" , "id" ] ) proddict = self . _lookup_product_in_cache ( product ) if "id" not in proddict : raise BugzillaError ( "Product '%s' not found" % product ) product_id = proddict [ "id" ] opts = { 'product_id' : product_id , 'field' : 'component' } names = self . _proxy . Bug . legal_values ( opts ) [ "values" ] self . _cache . component_names [ product_id ] = names return self . _cache . component_names [ product_id ] | Return a list of component names for the passed product . | 234 | 11 |
24,993 | def _process_include_fields ( self , include_fields , exclude_fields , extra_fields ) : def _convert_fields ( _in ) : if not _in : return _in for newname , oldname in self . _get_api_aliases ( ) : if oldname in _in : _in . remove ( oldname ) if newname not in _in : _in . append ( newname ) return _in ret = { } if self . _check_version ( 4 , 0 ) : if include_fields : include_fields = _convert_fields ( include_fields ) if "id" not in include_fields : include_fields . append ( "id" ) ret [ "include_fields" ] = include_fields if exclude_fields : exclude_fields = _convert_fields ( exclude_fields ) ret [ "exclude_fields" ] = exclude_fields if self . _supports_getbug_extra_fields : if extra_fields : ret [ "extra_fields" ] = _convert_fields ( extra_fields ) return ret | Internal helper to process include_fields lists | 235 | 8 |
24,994 | def _getbugs ( self , idlist , permissive , include_fields = None , exclude_fields = None , extra_fields = None ) : oldidlist = idlist idlist = [ ] for i in oldidlist : try : idlist . append ( int ( i ) ) except ValueError : # String aliases can be passed as well idlist . append ( i ) extra_fields = self . _listify ( extra_fields or [ ] ) extra_fields += self . _getbug_extra_fields getbugdata = { "ids" : idlist } if permissive : getbugdata [ "permissive" ] = 1 getbugdata . update ( self . _process_include_fields ( include_fields , exclude_fields , extra_fields ) ) r = self . _proxy . Bug . get ( getbugdata ) if self . _check_version ( 4 , 0 ) : bugdict = dict ( [ ( b [ 'id' ] , b ) for b in r [ 'bugs' ] ] ) else : bugdict = dict ( [ ( b [ 'id' ] , b [ 'internals' ] ) for b in r [ 'bugs' ] ] ) ret = [ ] for i in idlist : found = None if i in bugdict : found = bugdict [ i ] else : # Need to map an alias for valdict in bugdict . values ( ) : if i in self . _listify ( valdict . get ( "alias" , None ) ) : found = valdict break ret . append ( found ) return ret | Return a list of dicts of full bug info for each given bug id . bug ids that couldn t be found will return None instead of a dict . | 336 | 32 |
24,995 | def _getbug ( self , objid , * * kwargs ) : return self . _getbugs ( [ objid ] , permissive = False , * * kwargs ) [ 0 ] | Thin wrapper around _getbugs to handle the slight argument tweaks for fetching a single bug . The main bit is permissive = False which will tell bugzilla to raise an explicit error if we can t fetch that bug . | 43 | 46 |
24,996 | def getbug ( self , objid , include_fields = None , exclude_fields = None , extra_fields = None ) : data = self . _getbug ( objid , include_fields = include_fields , exclude_fields = exclude_fields , extra_fields = extra_fields ) return Bug ( self , dict = data , autorefresh = self . bug_autorefresh ) | Return a Bug object with the full complement of bug data already loaded . | 84 | 14 |
24,997 | def getbugs ( self , idlist , include_fields = None , exclude_fields = None , extra_fields = None , permissive = True ) : data = self . _getbugs ( idlist , include_fields = include_fields , exclude_fields = exclude_fields , extra_fields = extra_fields , permissive = permissive ) return [ ( b and Bug ( self , dict = b , autorefresh = self . bug_autorefresh ) ) or None for b in data ] | Return a list of Bug objects with the full complement of bug data already loaded . If there s a problem getting the data for a given id the corresponding item in the returned list will be None . | 107 | 39 |
24,998 | def update_tags ( self , idlist , tags_add = None , tags_remove = None ) : tags = { } if tags_add : tags [ "add" ] = self . _listify ( tags_add ) if tags_remove : tags [ "remove" ] = self . _listify ( tags_remove ) d = { "ids" : self . _listify ( idlist ) , "tags" : tags , } return self . _proxy . Bug . update_tags ( d ) | Updates the tags field for a bug . | 109 | 9 |
24,999 | def _attachment_uri ( self , attachid ) : att_uri = self . url . replace ( 'xmlrpc.cgi' , 'attachment.cgi' ) att_uri = att_uri + '?id=%s' % attachid return att_uri | Returns the URI for the given attachment ID . | 60 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.