repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ejeschke/ginga
ginga/examples/reference-viewer/MyGlobalPlugin.py
MyGlobalPlugin.build_gui
def build_gui(self, container): """ This method is called when the plugin is invoked. It builds the GUI used by the plugin into the widget layout passed as ``container``. This method could be called several times if the plugin is opened and closed. The method may be omitted if there is no GUI for the plugin. This specific example uses the GUI widget set agnostic wrappers to build the GUI, but you can also just as easily use explicit toolkit calls here if you only want to support one widget set. """ top = Widgets.VBox() top.set_border_width(4) # this is a little trick for making plugins that work either in # a vertical or horizontal orientation. It returns a box container, # a scroll widget and an orientation ('vertical', 'horizontal') vbox, sw, orientation = Widgets.get_oriented_box(container) vbox.set_border_width(4) vbox.set_spacing(2) # Take a text widget to show some instructions self.msg_font = self.fv.get_font("sans", 12) tw = Widgets.TextArea(wrap=True, editable=False) tw.set_font(self.msg_font) self.tw = tw # Frame for instructions and add the text widget with another # blank widget to stretch as needed to fill emp fr = Widgets.Frame("Status") fr.set_widget(tw) vbox.add_widget(fr, stretch=0) # Add a spacer to stretch the rest of the way to the end of the # plugin space spacer = Widgets.Label('') vbox.add_widget(spacer, stretch=1) # scroll bars will allow lots of content to be accessed top.add_widget(sw, stretch=1) # A button box that is always visible at the bottom btns = Widgets.HBox() btns.set_spacing(3) # Add a close button for the convenience of the user btn = Widgets.Button("Close") btn.add_callback('activated', lambda w: self.close()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) top.add_widget(btns, stretch=0) # Add our GUI to the container container.add_widget(top, stretch=1) # NOTE: if you are building a GUI using a specific widget toolkit # (e.g. Qt) GUI calls, you need to extract the widget or layout # from the non-toolkit specific container wrapper and call on that # to pack your widget, e.g.: #cw = container.get_widget() #cw.addWidget(widget, stretch=1) self.gui_up = True
python
def build_gui(self, container): """ This method is called when the plugin is invoked. It builds the GUI used by the plugin into the widget layout passed as ``container``. This method could be called several times if the plugin is opened and closed. The method may be omitted if there is no GUI for the plugin. This specific example uses the GUI widget set agnostic wrappers to build the GUI, but you can also just as easily use explicit toolkit calls here if you only want to support one widget set. """ top = Widgets.VBox() top.set_border_width(4) # this is a little trick for making plugins that work either in # a vertical or horizontal orientation. It returns a box container, # a scroll widget and an orientation ('vertical', 'horizontal') vbox, sw, orientation = Widgets.get_oriented_box(container) vbox.set_border_width(4) vbox.set_spacing(2) # Take a text widget to show some instructions self.msg_font = self.fv.get_font("sans", 12) tw = Widgets.TextArea(wrap=True, editable=False) tw.set_font(self.msg_font) self.tw = tw # Frame for instructions and add the text widget with another # blank widget to stretch as needed to fill emp fr = Widgets.Frame("Status") fr.set_widget(tw) vbox.add_widget(fr, stretch=0) # Add a spacer to stretch the rest of the way to the end of the # plugin space spacer = Widgets.Label('') vbox.add_widget(spacer, stretch=1) # scroll bars will allow lots of content to be accessed top.add_widget(sw, stretch=1) # A button box that is always visible at the bottom btns = Widgets.HBox() btns.set_spacing(3) # Add a close button for the convenience of the user btn = Widgets.Button("Close") btn.add_callback('activated', lambda w: self.close()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) top.add_widget(btns, stretch=0) # Add our GUI to the container container.add_widget(top, stretch=1) # NOTE: if you are building a GUI using a specific widget toolkit # (e.g. Qt) GUI calls, you need to extract the widget or layout # from the non-toolkit specific container wrapper and call on that # to pack your widget, e.g.: #cw = container.get_widget() #cw.addWidget(widget, stretch=1) self.gui_up = True
[ "def", "build_gui", "(", "self", ",", "container", ")", ":", "top", "=", "Widgets", ".", "VBox", "(", ")", "top", ".", "set_border_width", "(", "4", ")", "# this is a little trick for making plugins that work either in", "# a vertical or horizontal orientation. It return...
This method is called when the plugin is invoked. It builds the GUI used by the plugin into the widget layout passed as ``container``. This method could be called several times if the plugin is opened and closed. The method may be omitted if there is no GUI for the plugin. This specific example uses the GUI widget set agnostic wrappers to build the GUI, but you can also just as easily use explicit toolkit calls here if you only want to support one widget set.
[ "This", "method", "is", "called", "when", "the", "plugin", "is", "invoked", ".", "It", "builds", "the", "GUI", "used", "by", "the", "plugin", "into", "the", "widget", "layout", "passed", "as", "container", ".", "This", "method", "could", "be", "called", ...
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/reference-viewer/MyGlobalPlugin.py#L43-L106
train
25,000
ejeschke/ginga
ginga/examples/reference-viewer/MyGlobalPlugin.py
MyGlobalPlugin.focus_cb
def focus_cb(self, viewer, channel): """ Callback from the reference viewer shell when the focus changes between channels. """ chname = channel.name if self.active != chname: # focus has shifted to a different channel than our idea # of the active one self.active = chname self.set_info("Focus is now in channel '%s'" % ( self.active)) return True
python
def focus_cb(self, viewer, channel): """ Callback from the reference viewer shell when the focus changes between channels. """ chname = channel.name if self.active != chname: # focus has shifted to a different channel than our idea # of the active one self.active = chname self.set_info("Focus is now in channel '%s'" % ( self.active)) return True
[ "def", "focus_cb", "(", "self", ",", "viewer", ",", "channel", ")", ":", "chname", "=", "channel", ".", "name", "if", "self", ".", "active", "!=", "chname", ":", "# focus has shifted to a different channel than our idea", "# of the active one", "self", ".", "activ...
Callback from the reference viewer shell when the focus changes between channels.
[ "Callback", "from", "the", "reference", "viewer", "shell", "when", "the", "focus", "changes", "between", "channels", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/reference-viewer/MyGlobalPlugin.py#L136-L149
train
25,001
ejeschke/ginga
ginga/examples/reference-viewer/MyGlobalPlugin.py
MyGlobalPlugin.redo
def redo(self, channel, image): """ Called from the reference viewer shell when a new image has been added to a channel. """ chname = channel.name # Only update our GUI if the activity is in the focused # channel if self.active == chname: imname = image.get('name', 'NONAME') self.set_info("A new image '%s' has been added to channel %s" % ( imname, chname)) return True
python
def redo(self, channel, image): """ Called from the reference viewer shell when a new image has been added to a channel. """ chname = channel.name # Only update our GUI if the activity is in the focused # channel if self.active == chname: imname = image.get('name', 'NONAME') self.set_info("A new image '%s' has been added to channel %s" % ( imname, chname)) return True
[ "def", "redo", "(", "self", ",", "channel", ",", "image", ")", ":", "chname", "=", "channel", ".", "name", "# Only update our GUI if the activity is in the focused", "# channel", "if", "self", ".", "active", "==", "chname", ":", "imname", "=", "image", ".", "g...
Called from the reference viewer shell when a new image has been added to a channel.
[ "Called", "from", "the", "reference", "viewer", "shell", "when", "a", "new", "image", "has", "been", "added", "to", "a", "channel", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/reference-viewer/MyGlobalPlugin.py#L151-L164
train
25,002
ejeschke/ginga
ginga/misc/grc.py
_main
def _main(): """Run from command line.""" usage = "usage: %prog [options] cmd [arg] ..." optprs = OptionParser(usage=usage, version=version) optprs.add_option("--debug", dest="debug", default=False, action="store_true", help="Enter the pdb debugger on main()") optprs.add_option("--host", dest="host", metavar="HOST", default="localhost", help="Connect to server at HOST") optprs.add_option("--port", dest="port", type="int", default=9000, metavar="PORT", help="Connect to server at PORT") optprs.add_option("--profile", dest="profile", action="store_true", default=False, help="Run the profiler on main()") (options, args) = optprs.parse_args(sys.argv[1:]) # Are we debugging this? if options.debug: import pdb pdb.run('main(options, args)') # Are we profiling this? elif options.profile: import profile print("%s profile:" % sys.argv[0]) profile.run('main(options, args)') else: main(options, args)
python
def _main(): """Run from command line.""" usage = "usage: %prog [options] cmd [arg] ..." optprs = OptionParser(usage=usage, version=version) optprs.add_option("--debug", dest="debug", default=False, action="store_true", help="Enter the pdb debugger on main()") optprs.add_option("--host", dest="host", metavar="HOST", default="localhost", help="Connect to server at HOST") optprs.add_option("--port", dest="port", type="int", default=9000, metavar="PORT", help="Connect to server at PORT") optprs.add_option("--profile", dest="profile", action="store_true", default=False, help="Run the profiler on main()") (options, args) = optprs.parse_args(sys.argv[1:]) # Are we debugging this? if options.debug: import pdb pdb.run('main(options, args)') # Are we profiling this? elif options.profile: import profile print("%s profile:" % sys.argv[0]) profile.run('main(options, args)') else: main(options, args)
[ "def", "_main", "(", ")", ":", "usage", "=", "\"usage: %prog [options] cmd [arg] ...\"", "optprs", "=", "OptionParser", "(", "usage", "=", "usage", ",", "version", "=", "version", ")", "optprs", ".", "add_option", "(", "\"--debug\"", ",", "dest", "=", "\"debug...
Run from command line.
[ "Run", "from", "command", "line", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/grc.py#L49-L82
train
25,003
ejeschke/ginga
ginga/util/io_rgb.py
RGBFileHandler._imload
def _imload(self, filepath, kwds): """Load an image file, guessing the format, and return a numpy array containing an RGB image. If EXIF keywords can be read they are returned in the dict _kwds_. """ start_time = time.time() typ, enc = mimetypes.guess_type(filepath) if not typ: typ = 'image/jpeg' typ, subtyp = typ.split('/') self.logger.debug("MIME type is %s/%s" % (typ, subtyp)) data_loaded = False if have_opencv and subtyp not in ['gif']: # First choice is OpenCv, because it supports high-bit depth # multiband images means = 'opencv' data_np = cv2.imread(filepath, cv2.IMREAD_ANYDEPTH + cv2.IMREAD_ANYCOLOR) if data_np is not None: data_loaded = True # funky indexing because opencv returns BGR images, # whereas PIL and others return RGB if len(data_np.shape) >= 3 and data_np.shape[2] >= 3: data_np = data_np[..., :: -1] # OpenCv doesn't "do" image metadata, so we punt to piexif # library (if installed) self.piexif_getexif(filepath, kwds) # OpenCv added a feature to do auto-orientation when loading # (see https://github.com/opencv/opencv/issues/4344) # So reset these values to prevent auto-orientation from # happening later kwds['Orientation'] = 1 kwds['Image Orientation'] = 1 # convert to working color profile, if can if self.clr_mgr.can_profile(): data_np = self.clr_mgr.profile_to_working_numpy(data_np, kwds) if not data_loaded and have_pil: means = 'PIL' image = PILimage.open(filepath) try: if hasattr(image, '_getexif'): info = image._getexif() if info is not None: for tag, value in info.items(): kwd = TAGS.get(tag, tag) kwds[kwd] = value elif have_exif: self.piexif_getexif(image.info["exif"], kwds) else: self.logger.warning("Please install 'piexif' module to get image metadata") except Exception as e: self.logger.warning("Failed to get image metadata: %s" % (str(e))) # convert to working color profile, if can if self.clr_mgr.can_profile(): image = self.clr_mgr.profile_to_working_pil(image, kwds) # convert from PIL to numpy data_np = np.array(image) if data_np is not None: data_loaded = True if (not data_loaded and (typ == 'image') and (subtyp in ('x-portable-pixmap', 'x-portable-greymap'))): # Special opener for PPM files, preserves high bit depth means = 'built-in' data_np = open_ppm(filepath) if data_np is not None: data_loaded = True if not data_loaded: raise ImageError("No way to load image format '%s/%s'" % ( typ, subtyp)) end_time = time.time() self.logger.debug("loading (%s) time %.4f sec" % ( means, end_time - start_time)) return data_np
python
def _imload(self, filepath, kwds): """Load an image file, guessing the format, and return a numpy array containing an RGB image. If EXIF keywords can be read they are returned in the dict _kwds_. """ start_time = time.time() typ, enc = mimetypes.guess_type(filepath) if not typ: typ = 'image/jpeg' typ, subtyp = typ.split('/') self.logger.debug("MIME type is %s/%s" % (typ, subtyp)) data_loaded = False if have_opencv and subtyp not in ['gif']: # First choice is OpenCv, because it supports high-bit depth # multiband images means = 'opencv' data_np = cv2.imread(filepath, cv2.IMREAD_ANYDEPTH + cv2.IMREAD_ANYCOLOR) if data_np is not None: data_loaded = True # funky indexing because opencv returns BGR images, # whereas PIL and others return RGB if len(data_np.shape) >= 3 and data_np.shape[2] >= 3: data_np = data_np[..., :: -1] # OpenCv doesn't "do" image metadata, so we punt to piexif # library (if installed) self.piexif_getexif(filepath, kwds) # OpenCv added a feature to do auto-orientation when loading # (see https://github.com/opencv/opencv/issues/4344) # So reset these values to prevent auto-orientation from # happening later kwds['Orientation'] = 1 kwds['Image Orientation'] = 1 # convert to working color profile, if can if self.clr_mgr.can_profile(): data_np = self.clr_mgr.profile_to_working_numpy(data_np, kwds) if not data_loaded and have_pil: means = 'PIL' image = PILimage.open(filepath) try: if hasattr(image, '_getexif'): info = image._getexif() if info is not None: for tag, value in info.items(): kwd = TAGS.get(tag, tag) kwds[kwd] = value elif have_exif: self.piexif_getexif(image.info["exif"], kwds) else: self.logger.warning("Please install 'piexif' module to get image metadata") except Exception as e: self.logger.warning("Failed to get image metadata: %s" % (str(e))) # convert to working color profile, if can if self.clr_mgr.can_profile(): image = self.clr_mgr.profile_to_working_pil(image, kwds) # convert from PIL to numpy data_np = np.array(image) if data_np is not None: data_loaded = True if (not data_loaded and (typ == 'image') and (subtyp in ('x-portable-pixmap', 'x-portable-greymap'))): # Special opener for PPM files, preserves high bit depth means = 'built-in' data_np = open_ppm(filepath) if data_np is not None: data_loaded = True if not data_loaded: raise ImageError("No way to load image format '%s/%s'" % ( typ, subtyp)) end_time = time.time() self.logger.debug("loading (%s) time %.4f sec" % ( means, end_time - start_time)) return data_np
[ "def", "_imload", "(", "self", ",", "filepath", ",", "kwds", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "typ", ",", "enc", "=", "mimetypes", ".", "guess_type", "(", "filepath", ")", "if", "not", "typ", ":", "typ", "=", "'image/jpeg'"...
Load an image file, guessing the format, and return a numpy array containing an RGB image. If EXIF keywords can be read they are returned in the dict _kwds_.
[ "Load", "an", "image", "file", "guessing", "the", "format", "and", "return", "a", "numpy", "array", "containing", "an", "RGB", "image", ".", "If", "EXIF", "keywords", "can", "be", "read", "they", "are", "returned", "in", "the", "dict", "_kwds_", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/io_rgb.py#L125-L211
train
25,004
ejeschke/ginga
ginga/util/io_rgb.py
RGBFileHandler.imresize
def imresize(self, data, new_wd, new_ht, method='bilinear'): """Scale an image in numpy array _data_ to the specified width and height. A smooth scaling is preferred. """ old_ht, old_wd = data.shape[:2] start_time = time.time() if have_pilutil: means = 'PIL' zoom_x = float(new_wd) / float(old_wd) zoom_y = float(new_ht) / float(old_ht) if (old_wd >= new_wd) or (old_ht >= new_ht): # data size is bigger, skip pixels zoom = max(zoom_x, zoom_y) else: zoom = min(zoom_x, zoom_y) newdata = imresize(data, zoom, interp=method) else: raise ImageError("No way to scale image smoothly") end_time = time.time() self.logger.debug("scaling (%s) time %.4f sec" % ( means, end_time - start_time)) return newdata
python
def imresize(self, data, new_wd, new_ht, method='bilinear'): """Scale an image in numpy array _data_ to the specified width and height. A smooth scaling is preferred. """ old_ht, old_wd = data.shape[:2] start_time = time.time() if have_pilutil: means = 'PIL' zoom_x = float(new_wd) / float(old_wd) zoom_y = float(new_ht) / float(old_ht) if (old_wd >= new_wd) or (old_ht >= new_ht): # data size is bigger, skip pixels zoom = max(zoom_x, zoom_y) else: zoom = min(zoom_x, zoom_y) newdata = imresize(data, zoom, interp=method) else: raise ImageError("No way to scale image smoothly") end_time = time.time() self.logger.debug("scaling (%s) time %.4f sec" % ( means, end_time - start_time)) return newdata
[ "def", "imresize", "(", "self", ",", "data", ",", "new_wd", ",", "new_ht", ",", "method", "=", "'bilinear'", ")", ":", "old_ht", ",", "old_wd", "=", "data", ".", "shape", "[", ":", "2", "]", "start_time", "=", "time", ".", "time", "(", ")", "if", ...
Scale an image in numpy array _data_ to the specified width and height. A smooth scaling is preferred.
[ "Scale", "an", "image", "in", "numpy", "array", "_data_", "to", "the", "specified", "width", "and", "height", ".", "A", "smooth", "scaling", "is", "preferred", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/io_rgb.py#L265-L291
train
25,005
ejeschke/ginga
ginga/RGBMap.py
RGBPlanes.get_array
def get_array(self, order, dtype=None): """Get Numpy array that represents the RGB layers. Parameters ---------- order : str The desired order of RGB color layers. Returns ------- arr : ndarray Numpy array that represents the RGB layers. dtype : numpy array dtype (optional) Type of the numpy array desired. """ if dtype is None: dtype = self.rgbarr.dtype order = order.upper() if order == self.order: return self.rgbarr.astype(dtype, copy=False) res = trcalc.reorder_image(order, self.rgbarr, self.order) res = res.astype(dtype, copy=False, casting='unsafe') return res
python
def get_array(self, order, dtype=None): """Get Numpy array that represents the RGB layers. Parameters ---------- order : str The desired order of RGB color layers. Returns ------- arr : ndarray Numpy array that represents the RGB layers. dtype : numpy array dtype (optional) Type of the numpy array desired. """ if dtype is None: dtype = self.rgbarr.dtype order = order.upper() if order == self.order: return self.rgbarr.astype(dtype, copy=False) res = trcalc.reorder_image(order, self.rgbarr, self.order) res = res.astype(dtype, copy=False, casting='unsafe') return res
[ "def", "get_array", "(", "self", ",", "order", ",", "dtype", "=", "None", ")", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "self", ".", "rgbarr", ".", "dtype", "order", "=", "order", ".", "upper", "(", ")", "if", "order", "==", "self", "...
Get Numpy array that represents the RGB layers. Parameters ---------- order : str The desired order of RGB color layers. Returns ------- arr : ndarray Numpy array that represents the RGB layers. dtype : numpy array dtype (optional) Type of the numpy array desired.
[ "Get", "Numpy", "array", "that", "represents", "the", "RGB", "layers", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/RGBMap.py#L40-L65
train
25,006
ejeschke/ginga
ginga/RGBMap.py
RGBMapper.set_cmap
def set_cmap(self, cmap, callback=True): """ Set the color map used by this RGBMapper. `cmap` specifies a ColorMap object. If `callback` is True, then any callbacks associated with this change will be invoked. """ self.cmap = cmap with self.suppress_changed: self.calc_cmap() # TEMP: ignore passed callback parameter # callback=False in the following because we don't want to # recursively invoke set_cmap() self.t_.set(color_map=cmap.name, callback=False)
python
def set_cmap(self, cmap, callback=True): """ Set the color map used by this RGBMapper. `cmap` specifies a ColorMap object. If `callback` is True, then any callbacks associated with this change will be invoked. """ self.cmap = cmap with self.suppress_changed: self.calc_cmap() # TEMP: ignore passed callback parameter # callback=False in the following because we don't want to # recursively invoke set_cmap() self.t_.set(color_map=cmap.name, callback=False)
[ "def", "set_cmap", "(", "self", ",", "cmap", ",", "callback", "=", "True", ")", ":", "self", ".", "cmap", "=", "cmap", "with", "self", ".", "suppress_changed", ":", "self", ".", "calc_cmap", "(", ")", "# TEMP: ignore passed callback parameter", "# callback=Fal...
Set the color map used by this RGBMapper. `cmap` specifies a ColorMap object. If `callback` is True, then any callbacks associated with this change will be invoked.
[ "Set", "the", "color", "map", "used", "by", "this", "RGBMapper", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/RGBMap.py#L199-L212
train
25,007
ejeschke/ginga
ginga/RGBMap.py
RGBMapper.set_imap
def set_imap(self, imap, callback=True): """ Set the intensity map used by this RGBMapper. `imap` specifies an IntensityMap object. If `callback` is True, then any callbacks associated with this change will be invoked. """ self.imap = imap self.calc_imap() with self.suppress_changed: # TEMP: ignore passed callback parameter self.recalc() # callback=False in the following because we don't want to # recursively invoke set_imap() self.t_.set(intensity_map=imap.name, callback=False)
python
def set_imap(self, imap, callback=True): """ Set the intensity map used by this RGBMapper. `imap` specifies an IntensityMap object. If `callback` is True, then any callbacks associated with this change will be invoked. """ self.imap = imap self.calc_imap() with self.suppress_changed: # TEMP: ignore passed callback parameter self.recalc() # callback=False in the following because we don't want to # recursively invoke set_imap() self.t_.set(intensity_map=imap.name, callback=False)
[ "def", "set_imap", "(", "self", ",", "imap", ",", "callback", "=", "True", ")", ":", "self", ".", "imap", "=", "imap", "self", ".", "calc_imap", "(", ")", "with", "self", ".", "suppress_changed", ":", "# TEMP: ignore passed callback parameter", "self", ".", ...
Set the intensity map used by this RGBMapper. `imap` specifies an IntensityMap object. If `callback` is True, then any callbacks associated with this change will be invoked.
[ "Set", "the", "intensity", "map", "used", "by", "this", "RGBMapper", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/RGBMap.py#L273-L287
train
25,008
ejeschke/ginga
ginga/RGBMap.py
RGBMapper.stretch
def stretch(self, scale_factor, callback=True): """Stretch the color map via altering the shift map. """ self.scale_pct *= scale_factor self.scale_and_shift(self.scale_pct, 0.0, callback=callback)
python
def stretch(self, scale_factor, callback=True): """Stretch the color map via altering the shift map. """ self.scale_pct *= scale_factor self.scale_and_shift(self.scale_pct, 0.0, callback=callback)
[ "def", "stretch", "(", "self", ",", "scale_factor", ",", "callback", "=", "True", ")", ":", "self", ".", "scale_pct", "*=", "scale_factor", "self", ".", "scale_and_shift", "(", "self", ".", "scale_pct", ",", "0.0", ",", "callback", "=", "callback", ")" ]
Stretch the color map via altering the shift map.
[ "Stretch", "the", "color", "map", "via", "altering", "the", "shift", "map", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/RGBMap.py#L557-L561
train
25,009
ejeschke/ginga
ginga/rv/plugins/WCSMatch.py
WCSMatch._set_reference_channel_cb
def _set_reference_channel_cb(self, w, idx): """This is the GUI callback for the control that sets the reference channel. """ chname = self.chnames[idx] self._set_reference_channel(chname)
python
def _set_reference_channel_cb(self, w, idx): """This is the GUI callback for the control that sets the reference channel. """ chname = self.chnames[idx] self._set_reference_channel(chname)
[ "def", "_set_reference_channel_cb", "(", "self", ",", "w", ",", "idx", ")", ":", "chname", "=", "self", ".", "chnames", "[", "idx", "]", "self", ".", "_set_reference_channel", "(", "chname", ")" ]
This is the GUI callback for the control that sets the reference channel.
[ "This", "is", "the", "GUI", "callback", "for", "the", "control", "that", "sets", "the", "reference", "channel", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L192-L197
train
25,010
ejeschke/ginga
ginga/rv/plugins/WCSMatch.py
WCSMatch.set_reference_channel
def set_reference_channel(self, chname): """This is the API call to set the reference channel. """ # change the GUI control to match idx = self.chnames.index(str(chname)) self.w.ref_channel.set_index(idx) return self._set_reference_channel(chname)
python
def set_reference_channel(self, chname): """This is the API call to set the reference channel. """ # change the GUI control to match idx = self.chnames.index(str(chname)) self.w.ref_channel.set_index(idx) return self._set_reference_channel(chname)
[ "def", "set_reference_channel", "(", "self", ",", "chname", ")", ":", "# change the GUI control to match", "idx", "=", "self", ".", "chnames", ".", "index", "(", "str", "(", "chname", ")", ")", "self", ".", "w", ".", "ref_channel", ".", "set_index", "(", "...
This is the API call to set the reference channel.
[ "This", "is", "the", "API", "call", "to", "set", "the", "reference", "channel", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L199-L205
train
25,011
ejeschke/ginga
ginga/rv/plugins/WCSMatch.py
WCSMatch.zoomset_cb
def zoomset_cb(self, setting, value, chviewer, info): """This callback is called when a channel window is zoomed. """ return self.zoomset(chviewer, info.chinfo)
python
def zoomset_cb(self, setting, value, chviewer, info): """This callback is called when a channel window is zoomed. """ return self.zoomset(chviewer, info.chinfo)
[ "def", "zoomset_cb", "(", "self", ",", "setting", ",", "value", ",", "chviewer", ",", "info", ")", ":", "return", "self", ".", "zoomset", "(", "chviewer", ",", "info", ".", "chinfo", ")" ]
This callback is called when a channel window is zoomed.
[ "This", "callback", "is", "called", "when", "a", "channel", "window", "is", "zoomed", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L234-L237
train
25,012
ejeschke/ginga
ginga/rv/plugins/WCSMatch.py
WCSMatch.rotset_cb
def rotset_cb(self, setting, value, chviewer, info): """This callback is called when a channel window is rotated. """ return self.rotset(chviewer, info.chinfo)
python
def rotset_cb(self, setting, value, chviewer, info): """This callback is called when a channel window is rotated. """ return self.rotset(chviewer, info.chinfo)
[ "def", "rotset_cb", "(", "self", ",", "setting", ",", "value", ",", "chviewer", ",", "info", ")", ":", "return", "self", ".", "rotset", "(", "chviewer", ",", "info", ".", "chinfo", ")" ]
This callback is called when a channel window is rotated.
[ "This", "callback", "is", "called", "when", "a", "channel", "window", "is", "rotated", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L301-L304
train
25,013
ejeschke/ginga
ginga/rv/plugins/WCSMatch.py
WCSMatch.panset_cb
def panset_cb(self, setting, value, chviewer, info): """This callback is called when a channel window is panned. """ return self.panset(chviewer, info.chinfo)
python
def panset_cb(self, setting, value, chviewer, info): """This callback is called when a channel window is panned. """ return self.panset(chviewer, info.chinfo)
[ "def", "panset_cb", "(", "self", ",", "setting", ",", "value", ",", "chviewer", ",", "info", ")", ":", "return", "self", ".", "panset", "(", "chviewer", ",", "info", ".", "chinfo", ")" ]
This callback is called when a channel window is panned.
[ "This", "callback", "is", "called", "when", "a", "channel", "window", "is", "panned", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WCSMatch.py#L358-L361
train
25,014
ejeschke/ginga
ginga/web/jupyterw/JpHelp.py
TimerFactory.timer_tick
def timer_tick(self): """Callback executed every self.base_interval_msec to check timer expirations. """ # 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)
python
def timer_tick(self): """Callback executed every self.base_interval_msec to check timer expirations. """ # 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)
[ "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...
Callback executed every self.base_interval_msec to check timer expirations.
[ "Callback", "executed", "every", "self", ".", "base_interval_msec", "to", "check", "timer", "expirations", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/jupyterw/JpHelp.py#L45-L53
train
25,015
ejeschke/ginga
ginga/rv/plugins/ColorMapPicker.py
ColorMapPicker.select_cb
def select_cb(self, viewer, event, data_x, data_y): """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. """ 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)
python
def select_cb(self, viewer, event, data_x, data_y): """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. """ 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)
[ "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...
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.
[ "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", "...
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ColorMapPicker.py#L130-L149
train
25,016
ejeschke/ginga
ginga/rv/plugins/ColorMapPicker.py
ColorMapPicker.scroll_cb
def scroll_cb(self, viewer, direction, amt, data_x, data_y): """Called when the user scrolls in the color bar viewer. Pan up or down to show additional bars. """ 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)
python
def scroll_cb(self, viewer, direction, amt, data_x, data_y): """Called when the user scrolls in the color bar viewer. Pan up or down to show additional bars. """ 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)
[ "def", "scroll_cb", "(", "self", ",", "viewer", ",", "direction", ",", "amt", ",", "data_x", ",", "data_y", ")", ":", "bd", "=", "viewer", ".", "get_bindings", "(", ")", "direction", "=", "bd", ".", "get_direction", "(", "direction", ")", "pan_x", ",",...
Called when the user scrolls in the color bar viewer. Pan up or down to show additional bars.
[ "Called", "when", "the", "user", "scrolls", "in", "the", "color", "bar", "viewer", ".", "Pan", "up", "or", "down", "to", "show", "additional", "bars", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ColorMapPicker.py#L151-L166
train
25,017
ejeschke/ginga
ginga/rv/plugins/ColorMapPicker.py
ColorMapPicker.rebuild_cmaps
def rebuild_cmaps(self): """Builds a color RGB image containing color bars of all the possible color maps and their labels. """ 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)
python
def rebuild_cmaps(self): """Builds a color RGB image containing color bars of all the possible color maps and their labels. """ 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)
[ "def", "rebuild_cmaps", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"building color maps image\"", ")", "ht", ",", "wd", ",", "sep", "=", "self", ".", "_cmht", ",", "self", ".", "_cmwd", ",", "self", ".", "_cmsep", "viewer", "=", ...
Builds a color RGB image containing color bars of all the possible color maps and their labels.
[ "Builds", "a", "color", "RGB", "image", "containing", "color", "bars", "of", "all", "the", "possible", "color", "maps", "and", "their", "labels", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ColorMapPicker.py#L168-L215
train
25,018
ejeschke/ginga
ginga/gw/Desktop.py
Desktop.record_sizes
def record_sizes(self): """Record sizes of all container widgets in the layout. The sizes are recorded in the `params` mappings in the layout. """ 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))
python
def record_sizes(self): """Record sizes of all container widgets in the layout. The sizes are recorded in the `params` mappings in the layout. """ 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))
[ "def", "record_sizes", "(", "self", ")", ":", "for", "rec", "in", "self", ".", "node", ".", "values", "(", ")", ":", "w", "=", "rec", ".", "widget", "wd", ",", "ht", "=", "w", ".", "get_size", "(", ")", "rec", ".", "params", ".", "update", "(",...
Record sizes of all container widgets in the layout. The sizes are recorded in the `params` mappings in the layout.
[ "Record", "sizes", "of", "all", "container", "widgets", "in", "the", "layout", ".", "The", "sizes", "are", "recorded", "in", "the", "params", "mappings", "in", "the", "layout", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/gw/Desktop.py#L615-L639
train
25,019
ejeschke/ginga
ginga/rv/plugins/RC.py
GingaWrapper.help
def help(self, *args): """Get help for a remote interface method. Examples -------- help('ginga', `method`) name of the method for which you want help help('channel', `chname`, `method`) name of the method in the channel for which you want help Returns ------- help : string a help message """ 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>'")
python
def help(self, *args): """Get help for a remote interface method. Examples -------- help('ginga', `method`) name of the method for which you want help help('channel', `chname`, `method`) name of the method in the channel for which you want help Returns ------- help : string a help message """ 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>'")
[ "def", "help", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "return", "help_msg", "which", "=", "args", "[", "0", "]", ".", "lower", "(", ")", "if", "which", "==", "'ginga'", ":", "method", "=", "args"...
Get help for a remote interface method. Examples -------- help('ginga', `method`) name of the method for which you want help help('channel', `chname`, `method`) name of the method in the channel for which you want help Returns ------- help : string a help message
[ "Get", "help", "for", "a", "remote", "interface", "method", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/RC.py#L300-L335
train
25,020
ejeschke/ginga
ginga/rv/plugins/RC.py
GingaWrapper.load_buffer
def load_buffer(self, imname, chname, img_buf, dims, dtype, header, metadata, compressed): """Display a FITS image buffer. Parameters ---------- imname : string a name to use for the image in Ginga chname : string channel in which to load the image img_buf : string the image data, as a bytes object dims : tuple image dimensions in pixels (usually (height, width)) dtype : string numpy data type of encoding (e.g. 'float32') header : dict fits file header as a dictionary metadata : dict other metadata about image to attach to image compressed : bool decompress buffer using "bz2" Returns ------- 0 Notes ----- * Get array dims: data.shape * Get array dtype: str(data.dtype) * Make a string from a numpy array: buf = data.tostring() * Compress the buffer: buf = bz2.compress(buf) """ 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
python
def load_buffer(self, imname, chname, img_buf, dims, dtype, header, metadata, compressed): """Display a FITS image buffer. Parameters ---------- imname : string a name to use for the image in Ginga chname : string channel in which to load the image img_buf : string the image data, as a bytes object dims : tuple image dimensions in pixels (usually (height, width)) dtype : string numpy data type of encoding (e.g. 'float32') header : dict fits file header as a dictionary metadata : dict other metadata about image to attach to image compressed : bool decompress buffer using "bz2" Returns ------- 0 Notes ----- * Get array dims: data.shape * Get array dtype: str(data.dtype) * Make a string from a numpy array: buf = data.tostring() * Compress the buffer: buf = bz2.compress(buf) """ 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
[ "def", "load_buffer", "(", "self", ",", "imname", ",", "chname", ",", "img_buf", ",", "dims", ",", "dtype", ",", "header", ",", "metadata", ",", "compressed", ")", ":", "self", ".", "logger", ".", "info", "(", "\"received image data len=%d\"", "%", "(", ...
Display a FITS image buffer. Parameters ---------- imname : string a name to use for the image in Ginga chname : string channel in which to load the image img_buf : string the image data, as a bytes object dims : tuple image dimensions in pixels (usually (height, width)) dtype : string numpy data type of encoding (e.g. 'float32') header : dict fits file header as a dictionary metadata : dict other metadata about image to attach to image compressed : bool decompress buffer using "bz2" Returns ------- 0 Notes ----- * Get array dims: data.shape * Get array dtype: str(data.dtype) * Make a string from a numpy array: buf = data.tostring() * Compress the buffer: buf = bz2.compress(buf)
[ "Display", "a", "FITS", "image", "buffer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/RC.py#L337-L411
train
25,021
ejeschke/ginga
ginga/toolkit.py
use
def use(name): """ Set the name of the GUI toolkit we should use. """ 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
python
def use(name): """ Set the name of the GUI toolkit we should use. """ 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
[ "def", "use", "(", "name", ")", ":", "global", "toolkit", ",", "family", "name", "=", "name", ".", "lower", "(", ")", "if", "name", ".", "startswith", "(", "'choose'", ")", ":", "pass", "elif", "name", ".", "startswith", "(", "'qt'", ")", "or", "na...
Set the name of the GUI toolkit we should use.
[ "Set", "the", "name", "of", "the", "GUI", "toolkit", "we", "should", "use", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/toolkit.py#L16-L57
train
25,022
ejeschke/ginga
ginga/misc/Settings.py
SettingGroup.share_settings
def share_settings(self, other, keylist=None, include_callbacks=True, callback=True): """Sharing settings with `other` """ 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)
python
def share_settings(self, other, keylist=None, include_callbacks=True, callback=True): """Sharing settings with `other` """ 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)
[ "def", "share_settings", "(", "self", ",", "other", ",", "keylist", "=", "None", ",", "include_callbacks", "=", "True", ",", "callback", "=", "True", ")", ":", "if", "keylist", "is", "None", ":", "keylist", "=", "self", ".", "group", ".", "keys", "(", ...
Sharing settings with `other`
[ "Sharing", "settings", "with", "other" ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Settings.py#L107-L122
train
25,023
ejeschke/ginga
ginga/util/wcsmod/__init__.py
use
def use(wcspkg, raise_err=True): """Choose WCS package.""" 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
python
def use(wcspkg, raise_err=True): """Choose WCS package.""" 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
[ "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'", "%", ...
Choose WCS package.
[ "Choose", "WCS", "package", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcsmod/__init__.py#L63-L83
train
25,024
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
PlotTable._set_combobox
def _set_combobox(self, attrname, vals, default=0): """Populate combobox with given list.""" 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
python
def _set_combobox(self, attrname, vals, default=0): """Populate combobox with given list.""" 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
[ "def", "_set_combobox", "(", "self", ",", "attrname", ",", "vals", ",", "default", "=", "0", ")", ":", "combobox", "=", "getattr", "(", "self", ".", "w", ",", "attrname", ")", "for", "val", "in", "vals", ":", "combobox", ".", "append_text", "(", "val...
Populate combobox with given list.
[ "Populate", "combobox", "with", "given", "list", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L177-L186
train
25,025
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
PlotTable.clear_data
def clear_data(self): """Clear comboboxes and columns.""" 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('')
python
def clear_data(self): """Clear comboboxes and columns.""" 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('')
[ "def", "clear_data", "(", "self", ")", ":", "self", ".", "tab", "=", "None", "self", ".", "cols", "=", "[", "]", "self", ".", "_idx", "=", "[", "]", "self", ".", "x_col", "=", "''", "self", ".", "y_col", "=", "''", "self", ".", "w", ".", "xco...
Clear comboboxes and columns.
[ "Clear", "comboboxes", "and", "columns", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L217-L229
train
25,026
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
PlotTable.clear_plot
def clear_plot(self): """Clear plot display.""" self.tab_plot.clear() self.tab_plot.draw() self.save_plot.set_enabled(False)
python
def clear_plot(self): """Clear plot display.""" self.tab_plot.clear() self.tab_plot.draw() self.save_plot.set_enabled(False)
[ "def", "clear_plot", "(", "self", ")", ":", "self", ".", "tab_plot", ".", "clear", "(", ")", "self", ".", "tab_plot", ".", "draw", "(", ")", "self", ".", "save_plot", ".", "set_enabled", "(", "False", ")" ]
Clear plot display.
[ "Clear", "plot", "display", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L231-L235
train
25,027
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
PlotTable.plot_two_columns
def plot_two_columns(self, reset_xlimits=False, reset_ylimits=False): """Simple line plot for two selected columns.""" 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)
python
def plot_two_columns(self, reset_xlimits=False, reset_ylimits=False): """Simple line plot for two selected columns.""" 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)
[ "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", "=", ...
Simple line plot for two selected columns.
[ "Simple", "line", "plot", "for", "two", "selected", "columns", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L237-L274
train
25,028
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
PlotTable._get_plot_data
def _get_plot_data(self): """Extract only good data point for plotting.""" _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
python
def _get_plot_data(self): """Extract only good data point for plotting.""" _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
[ "def", "_get_plot_data", "(", "self", ")", ":", "_marker_type", "=", "self", ".", "settings", ".", "get", "(", "'markerstyle'", ",", "'o'", ")", "if", "self", ".", "x_col", "==", "self", ".", "_idxname", ":", "x_data", "=", "self", ".", "_idx", "else",...
Extract only good data point for plotting.
[ "Extract", "only", "good", "data", "point", "for", "plotting", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L292-L329
train
25,029
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
PlotTable._get_label
def _get_label(self, axis): """Return plot label for column for the given 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
python
def _get_label(self, axis): """Return plot label for column for the given 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
[ "def", "_get_label", "(", "self", ",", "axis", ")", ":", "if", "axis", "==", "'x'", ":", "colname", "=", "self", ".", "x_col", "else", ":", "# y", "colname", "=", "self", ".", "y_col", "if", "colname", "==", "self", ".", "_idxname", ":", "label", "...
Return plot label for column for the given axis.
[ "Return", "plot", "label", "for", "column", "for", "the", "given", "axis", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L331-L348
train
25,030
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
PlotTable.x_select_cb
def x_select_cb(self, w, index): """Callback to set X-axis column.""" try: self.x_col = self.cols[index] except IndexError as e: self.logger.error(str(e)) else: self.plot_two_columns(reset_xlimits=True)
python
def x_select_cb(self, w, index): """Callback to set X-axis column.""" try: self.x_col = self.cols[index] except IndexError as e: self.logger.error(str(e)) else: self.plot_two_columns(reset_xlimits=True)
[ "def", "x_select_cb", "(", "self", ",", "w", ",", "index", ")", ":", "try", ":", "self", ".", "x_col", "=", "self", ".", "cols", "[", "index", "]", "except", "IndexError", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "str", "(", "e",...
Callback to set X-axis column.
[ "Callback", "to", "set", "X", "-", "axis", "column", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L350-L357
train
25,031
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
PlotTable.y_select_cb
def y_select_cb(self, w, index): """Callback to set Y-axis column.""" try: self.y_col = self.cols[index] except IndexError as e: self.logger.error(str(e)) else: self.plot_two_columns(reset_ylimits=True)
python
def y_select_cb(self, w, index): """Callback to set Y-axis column.""" try: self.y_col = self.cols[index] except IndexError as e: self.logger.error(str(e)) else: self.plot_two_columns(reset_ylimits=True)
[ "def", "y_select_cb", "(", "self", ",", "w", ",", "index", ")", ":", "try", ":", "self", ".", "y_col", "=", "self", ".", "cols", "[", "index", "]", "except", "IndexError", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "str", "(", "e",...
Callback to set Y-axis column.
[ "Callback", "to", "set", "Y", "-", "axis", "column", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L359-L366
train
25,032
ejeschke/ginga
ginga/rv/plugins/PlotTable.py
PlotTable.save_cb
def save_cb(self): """Save plot to file.""" # 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))
python
def save_cb(self): """Save plot to file.""" # 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))
[ "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", "(", ...
Save plot to file.
[ "Save", "plot", "to", "file", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L432-L458
train
25,033
ejeschke/ginga
ginga/examples/gtk/fits2pdf.py
convert
def convert(filepath, outfilepath): """Convert FITS image to PDF.""" 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()
python
def convert(filepath, outfilepath): """Convert FITS image to PDF.""" 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()
[ "def", "convert", "(", "filepath", ",", "outfilepath", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"example1\"", ")", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "fmt", "=", "logging", ".", "Formatter", "(", "STD_FORMAT", ...
Convert FITS image to PDF.
[ "Convert", "FITS", "image", "to", "PDF", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/gtk/fits2pdf.py#L35-L73
train
25,034
ejeschke/ginga
ginga/rv/plugins/TVMask.py
TVMask.redo
def redo(self): """Image or masks have changed. Clear and redraw.""" 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()
python
def redo(self): """Image or masks have changed. Clear and redraw.""" 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()
[ "def", "redo", "(", "self", ")", ":", "if", "not", "self", ".", "gui_up", ":", "return", "self", ".", "clear_mask", "(", ")", "image", "=", "self", ".", "fitsimage", ".", "get_image", "(", ")", "if", "image", "is", "None", ":", "return", "n_obj", "...
Image or masks have changed. Clear and redraw.
[ "Image", "or", "masks", "have", "changed", ".", "Clear", "and", "redraw", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L207-L228
train
25,035
ejeschke/ginga
ginga/rv/plugins/TVMask.py
TVMask.clear_mask
def clear_mask(self): """Clear mask from image. This does not clear loaded masks from memory.""" 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()
python
def clear_mask(self): """Clear mask from image. This does not clear loaded masks from memory.""" 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()
[ "def", "clear_mask", "(", "self", ")", ":", "if", "self", ".", "masktag", ":", "try", ":", "self", ".", "canvas", ".", "delete_object_by_tag", "(", "self", ".", "masktag", ",", "redraw", "=", "False", ")", "except", "Exception", ":", "pass", "if", "sel...
Clear mask from image. This does not clear loaded masks from memory.
[ "Clear", "mask", "from", "image", ".", "This", "does", "not", "clear", "loaded", "masks", "from", "memory", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L230-L246
train
25,036
ejeschke/ginga
ginga/rv/plugins/TVMask.py
TVMask.load_file
def load_file(self, filename): """Load mask image. Results are appended to previously loaded masks. This can be used to load mask per color. """ 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()
python
def load_file(self, filename): """Load mask image. Results are appended to previously loaded masks. This can be used to load mask per color. """ 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()
[ "def", "load_file", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "self", ".", "logger", ".", "info", "(", "'Loading mask image from {0}'", ".", "format", "(", "filename", ")",...
Load mask image. Results are appended to previously loaded masks. This can be used to load mask per color.
[ "Load", "mask", "image", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L257-L296
train
25,037
ejeschke/ginga
ginga/rv/plugins/TVMask.py
TVMask._rgbtomask
def _rgbtomask(self, obj): """Convert RGB arrays from mask canvas object back to boolean mask.""" dat = obj.get_image().get_data() # RGB arrays return dat.sum(axis=2).astype(np.bool)
python
def _rgbtomask(self, obj): """Convert RGB arrays from mask canvas object back to boolean mask.""" dat = obj.get_image().get_data() # RGB arrays return dat.sum(axis=2).astype(np.bool)
[ "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.
[ "Convert", "RGB", "arrays", "from", "mask", "canvas", "object", "back", "to", "boolean", "mask", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L317-L320
train
25,038
ejeschke/ginga
ginga/rv/plugins/TVMask.py
TVMask.hl_table2canvas
def hl_table2canvas(self, w, res_dict): """Highlight mask on canvas when user click on table.""" 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()
python
def hl_table2canvas(self, w, res_dict): """Highlight mask on canvas when user click on table.""" 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()
[ "def", "hl_table2canvas", "(", "self", ",", "w", ",", "res_dict", ")", ":", "objlist", "=", "[", "]", "# Remove existing highlight", "if", "self", ".", "maskhltag", ":", "try", ":", "self", ".", "canvas", ".", "delete_object_by_tag", "(", "self", ".", "mas...
Highlight mask on canvas when user click on table.
[ "Highlight", "mask", "on", "canvas", "when", "user", "click", "on", "table", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L322-L345
train
25,039
ejeschke/ginga
ginga/rv/plugins/TVMask.py
TVMask.hl_canvas2table_box
def hl_canvas2table_box(self, canvas, tag): """Highlight all masks inside user drawn box on table.""" 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])
python
def hl_canvas2table_box(self, canvas, tag): """Highlight all masks inside user drawn box on table.""" 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])
[ "def", "hl_canvas2table_box", "(", "self", ",", "canvas", ",", "tag", ")", ":", "self", ".", "treeview", ".", "clear_selection", "(", ")", "# Remove existing box", "cobj", "=", "canvas", ".", "get_object_by_tag", "(", "tag", ")", "if", "cobj", ".", "kind", ...
Highlight all masks inside user drawn box on table.
[ "Highlight", "all", "masks", "inside", "user", "drawn", "box", "on", "table", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L347-L388
train
25,040
ejeschke/ginga
ginga/rv/plugins/TVMask.py
TVMask.hl_canvas2table
def hl_canvas2table(self, canvas, button, data_x, data_y): """Highlight mask on table when user click on canvas.""" 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])
python
def hl_canvas2table(self, canvas, button, data_x, data_y): """Highlight mask on table when user click on canvas.""" 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])
[ "def", "hl_canvas2table", "(", "self", ",", "canvas", ",", "button", ",", "data_x", ",", "data_y", ")", ":", "self", ".", "treeview", ".", "clear_selection", "(", ")", "# Remove existing highlight", "if", "self", ".", "maskhltag", ":", "try", ":", "canvas", ...
Highlight mask on table when user click on canvas.
[ "Highlight", "mask", "on", "table", "when", "user", "click", "on", "canvas", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMask.py#L391-L420
train
25,041
ejeschke/ginga
ginga/canvas/types/astro.py
AnnulusMixin.contains_pt
def contains_pt(self, pt): """Containment test.""" obj1, obj2 = self.objects return obj2.contains_pt(pt) and np.logical_not(obj1.contains_pt(pt))
python
def contains_pt(self, pt): """Containment test.""" obj1, obj2 = self.objects return obj2.contains_pt(pt) and np.logical_not(obj1.contains_pt(pt))
[ "def", "contains_pt", "(", "self", ",", "pt", ")", ":", "obj1", ",", "obj2", "=", "self", ".", "objects", "return", "obj2", ".", "contains_pt", "(", "pt", ")", "and", "np", ".", "logical_not", "(", "obj1", ".", "contains_pt", "(", "pt", ")", ")" ]
Containment test.
[ "Containment", "test", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/types/astro.py#L561-L564
train
25,042
ejeschke/ginga
ginga/canvas/types/astro.py
AnnulusMixin.contains_pts
def contains_pts(self, pts): """Containment test on arrays.""" obj1, obj2 = self.objects arg1 = obj2.contains_pts(pts) arg2 = np.logical_not(obj1.contains_pts(pts)) return np.logical_and(arg1, arg2)
python
def contains_pts(self, pts): """Containment test on arrays.""" obj1, obj2 = self.objects arg1 = obj2.contains_pts(pts) arg2 = np.logical_not(obj1.contains_pts(pts)) return np.logical_and(arg1, arg2)
[ "def", "contains_pts", "(", "self", ",", "pts", ")", ":", "obj1", ",", "obj2", "=", "self", ".", "objects", "arg1", "=", "obj2", ".", "contains_pts", "(", "pts", ")", "arg2", "=", "np", ".", "logical_not", "(", "obj1", ".", "contains_pts", "(", "pts"...
Containment test on arrays.
[ "Containment", "test", "on", "arrays", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/types/astro.py#L566-L571
train
25,043
ejeschke/ginga
ginga/util/wcsmod/common.py
register_wcs
def register_wcs(name, wrapper_class, coord_types): """ Register a custom WCS wrapper. Parameters ---------- name : str The name of the custom WCS wrapper wrapper_class : subclass of `~ginga.util.wcsmod.BaseWCS` The class implementing the WCS wrapper coord_types : list of str List of names of coordinate types supported by the WCS """ global custom_wcs custom_wcs[name] = Bunch.Bunch(name=name, wrapper_class=wrapper_class, coord_types=coord_types)
python
def register_wcs(name, wrapper_class, coord_types): """ Register a custom WCS wrapper. Parameters ---------- name : str The name of the custom WCS wrapper wrapper_class : subclass of `~ginga.util.wcsmod.BaseWCS` The class implementing the WCS wrapper coord_types : list of str List of names of coordinate types supported by the WCS """ global custom_wcs custom_wcs[name] = Bunch.Bunch(name=name, wrapper_class=wrapper_class, coord_types=coord_types)
[ "def", "register_wcs", "(", "name", ",", "wrapper_class", ",", "coord_types", ")", ":", "global", "custom_wcs", "custom_wcs", "[", "name", "]", "=", "Bunch", ".", "Bunch", "(", "name", "=", "name", ",", "wrapper_class", "=", "wrapper_class", ",", "coord_type...
Register a custom WCS wrapper. Parameters ---------- name : str The name of the custom WCS wrapper wrapper_class : subclass of `~ginga.util.wcsmod.BaseWCS` The class implementing the WCS wrapper coord_types : list of str List of names of coordinate types supported by the WCS
[ "Register", "a", "custom", "WCS", "wrapper", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcsmod/common.py#L315-L333
train
25,044
ejeschke/ginga
ginga/util/wcsmod/common.py
choose_coord_units
def choose_coord_units(header): """Return the appropriate key code for the units value for the axes by examining the FITS 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'
python
def choose_coord_units(header): """Return the appropriate key code for the units value for the axes by examining the FITS 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'
[ "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...
Return the appropriate key code for the units value for the axes by examining the FITS header.
[ "Return", "the", "appropriate", "key", "code", "for", "the", "units", "value", "for", "the", "axes", "by", "examining", "the", "FITS", "header", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcsmod/common.py#L336-L346
train
25,045
ejeschke/ginga
ginga/util/wcsmod/common.py
get_coord_system_name
def get_coord_system_name(header): """Return an appropriate key code for the axes coordinate system by examining the FITS 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'
python
def get_coord_system_name(header): """Return an appropriate key code for the axes coordinate system by examining the FITS 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'
[ "def", "get_coord_system_name", "(", "header", ")", ":", "try", ":", "ctype", "=", "header", "[", "'CTYPE1'", "]", ".", "strip", "(", ")", ".", "upper", "(", ")", "except", "KeyError", ":", "try", ":", "# see if we have an \"RA\" header", "ra", "=", "heade...
Return an appropriate key code for the axes coordinate system by examining the FITS header.
[ "Return", "an", "appropriate", "key", "code", "for", "the", "axes", "coordinate", "system", "by", "examining", "the", "FITS", "header", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcsmod/common.py#L349-L425
train
25,046
ejeschke/ginga
ginga/util/wcsmod/common.py
BaseWCS.datapt_to_wcspt
def datapt_to_wcspt(self, datapt, coords='data', naxispath=None): """ Convert multiple data points to WCS. Parameters ---------- datapt : array-like Pixel coordinates in the format of ``[[x0, y0, ...], [x1, y1, ...], ..., [xn, yn, ...]]``. coords : 'data' or None, optional, default to 'data' Expresses whether the data coordinate is indexed from zero. naxispath : list-like or None, optional, defaults to None A sequence defining the pixel indexes > 2D, if any. Returns ------- wcspt : array-like WCS coordinates in the format of ``[[ra0, dec0], [ra1, dec1], ..., [ran, decn]]``. """ # 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])
python
def datapt_to_wcspt(self, datapt, coords='data', naxispath=None): """ Convert multiple data points to WCS. Parameters ---------- datapt : array-like Pixel coordinates in the format of ``[[x0, y0, ...], [x1, y1, ...], ..., [xn, yn, ...]]``. coords : 'data' or None, optional, default to 'data' Expresses whether the data coordinate is indexed from zero. naxispath : list-like or None, optional, defaults to None A sequence defining the pixel indexes > 2D, if any. Returns ------- wcspt : array-like WCS coordinates in the format of ``[[ra0, dec0], [ra1, dec1], ..., [ran, decn]]``. """ # 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])
[ "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", "NotImplem...
Convert multiple data points to WCS. Parameters ---------- datapt : array-like Pixel coordinates in the format of ``[[x0, y0, ...], [x1, y1, ...], ..., [xn, yn, ...]]``. coords : 'data' or None, optional, default to 'data' Expresses whether the data coordinate is indexed from zero. naxispath : list-like or None, optional, defaults to None A sequence defining the pixel indexes > 2D, if any. Returns ------- wcspt : array-like WCS coordinates in the format of ``[[ra0, dec0], [ra1, dec1], ..., [ran, decn]]``.
[ "Convert", "multiple", "data", "points", "to", "WCS", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcsmod/common.py#L191-L220
train
25,047
ejeschke/ginga
ginga/util/wcsmod/common.py
BaseWCS.wcspt_to_datapt
def wcspt_to_datapt(self, wcspt, coords='data', naxispath=None): """ Convert multiple WCS to data points. Parameters ---------- wcspt : array-like WCS coordinates in the format of ``[[ra0, dec0, ...], [ra1, dec1, ...], ..., [ran, decn, ...]]``. coords : 'data' or None, optional, default to 'data' Expresses whether the data coordinate is indexed from zero. naxispath : list-like or None, optional, defaults to None A sequence defining the pixel indexes > 2D, if any. Returns ------- datapt : array-like Pixel coordinates in the format of ``[[x0, y0], [x1, y1], ..., [xn, yn]]``. """ # 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])
python
def wcspt_to_datapt(self, wcspt, coords='data', naxispath=None): """ Convert multiple WCS to data points. Parameters ---------- wcspt : array-like WCS coordinates in the format of ``[[ra0, dec0, ...], [ra1, dec1, ...], ..., [ran, decn, ...]]``. coords : 'data' or None, optional, default to 'data' Expresses whether the data coordinate is indexed from zero. naxispath : list-like or None, optional, defaults to None A sequence defining the pixel indexes > 2D, if any. Returns ------- datapt : array-like Pixel coordinates in the format of ``[[x0, y0], [x1, y1], ..., [xn, yn]]``. """ # 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])
[ "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", "NotImpleme...
Convert multiple WCS to data points. Parameters ---------- wcspt : array-like WCS coordinates in the format of ``[[ra0, dec0, ...], [ra1, dec1, ...], ..., [ran, decn, ...]]``. coords : 'data' or None, optional, default to 'data' Expresses whether the data coordinate is indexed from zero. naxispath : list-like or None, optional, defaults to None A sequence defining the pixel indexes > 2D, if any. Returns ------- datapt : array-like Pixel coordinates in the format of ``[[x0, y0], [x1, y1], ..., [xn, yn]]``.
[ "Convert", "multiple", "WCS", "to", "data", "points", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcsmod/common.py#L222-L251
train
25,048
ejeschke/ginga
ginga/util/wcsmod/common.py
BaseWCS.fix_bad_headers
def fix_bad_headers(self): """ Fix up bad headers that cause problems for the wrapped WCS module. Subclass can override this method to fix up issues with the header for problem FITS files. """ # 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'
python
def fix_bad_headers(self): """ Fix up bad headers that cause problems for the wrapped WCS module. Subclass can override this method to fix up issues with the header for problem FITS files. """ # 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'
[ "def", "fix_bad_headers", "(", "self", ")", ":", "# WCSLIB doesn't like \"nonstandard\" units", "unit", "=", "self", ".", "header", ".", "get", "(", "'CUNIT1'", ",", "'deg'", ")", "if", "unit", ".", "upper", "(", ")", "==", "'DEGREE'", ":", "# self.header.upda...
Fix up bad headers that cause problems for the wrapped WCS module. Subclass can override this method to fix up issues with the header for problem FITS files.
[ "Fix", "up", "bad", "headers", "that", "cause", "problems", "for", "the", "wrapped", "WCS", "module", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/wcsmod/common.py#L291-L307
train
25,049
ejeschke/ginga
ginga/opengl/Camera.py
fov_for_height_and_distance
def fov_for_height_and_distance(height, distance): """Calculate the FOV needed to get a given frustum height at a given distance. """ vfov_deg = np.degrees(2.0 * np.arctan(height * 0.5 / distance)) return vfov_deg
python
def fov_for_height_and_distance(height, distance): """Calculate the FOV needed to get a given frustum height at a given distance. """ vfov_deg = np.degrees(2.0 * np.arctan(height * 0.5 / distance)) return vfov_deg
[ "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.
[ "Calculate", "the", "FOV", "needed", "to", "get", "a", "given", "frustum", "height", "at", "a", "given", "distance", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/opengl/Camera.py#L249-L254
train
25,050
ejeschke/ginga
ginga/opengl/Camera.py
Camera.set_gl_transform
def set_gl_transform(self): """This side effects the OpenGL context to set the view to match the camera. """ 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())
python
def set_gl_transform(self): """This side effects the OpenGL context to set the view to match the camera. """ 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())
[ "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 t...
This side effects the OpenGL context to set the view to match the camera.
[ "This", "side", "effects", "the", "OpenGL", "context", "to", "set", "the", "view", "to", "match", "the", "camera", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/opengl/Camera.py#L101-L123
train
25,051
ejeschke/ginga
ginga/opengl/Camera.py
Camera.get_translation_speed
def get_translation_speed(self, distance_from_target): """Returns the translation speed for ``distance_from_target`` in units per radius. """ return (distance_from_target * np.tan(self.fov_deg / 2.0 / 180.0 * np.pi))
python
def get_translation_speed(self, distance_from_target): """Returns the translation speed for ``distance_from_target`` in units per radius. """ return (distance_from_target * np.tan(self.fov_deg / 2.0 / 180.0 * np.pi))
[ "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.
[ "Returns", "the", "translation", "speed", "for", "distance_from_target", "in", "units", "per", "radius", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/opengl/Camera.py#L125-L130
train
25,052
ejeschke/ginga
ginga/opengl/Camera.py
Camera.orbit
def orbit(self, x1_px, y1_px, x2_px, y2_px): """ Causes the camera to "orbit" around the target point. This is also called "tumbling" in some software packages. """ 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
python
def orbit(self, x1_px, y1_px, x2_px, y2_px): """ Causes the camera to "orbit" around the target point. This is also called "tumbling" in some software packages. """ 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
[ "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", "*", ...
Causes the camera to "orbit" around the target point. This is also called "tumbling" in some software packages.
[ "Causes", "the", "camera", "to", "orbit", "around", "the", "target", "point", ".", "This", "is", "also", "called", "tumbling", "in", "some", "software", "packages", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/opengl/Camera.py#L132-L153
train
25,053
ejeschke/ginga
ginga/opengl/Camera.py
Camera.track
def track(self, delta_pixels, push_target=False, adj_fov=False): """ 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. If ``push_target'' is True, the point of interest translates forward (or backward) *with* the camera, i.e. it's "pushed" along with the camera; otherwise it remains stationary. if ``adj_fov`` is True then the camera's FOV is adjusted to keep the target at the same size as before (so called "dolly zoom" or "trombone effect"). """ 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
python
def track(self, delta_pixels, push_target=False, adj_fov=False): """ 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. If ``push_target'' is True, the point of interest translates forward (or backward) *with* the camera, i.e. it's "pushed" along with the camera; otherwise it remains stationary. if ``adj_fov`` is True then the camera's FOV is adjusted to keep the target at the same size as before (so called "dolly zoom" or "trombone effect"). """ 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
[ "def", "track", "(", "self", ",", "delta_pixels", ",", "push_target", "=", "False", ",", "adj_fov", "=", "False", ")", ":", "direction", "=", "self", ".", "target", "-", "self", ".", "position", "distance_from_target", "=", "direction", ".", "length", "(",...
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. If ``push_target'' is True, the point of interest translates forward (or backward) *with* the camera, i.e. it's "pushed" along with the camera; otherwise it remains stationary. if ``adj_fov`` is True then the camera's FOV is adjusted to keep the target at the same size as before (so called "dolly zoom" or "trombone effect").
[ "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",...
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/opengl/Camera.py#L177-L220
train
25,054
ejeschke/ginga
ginga/examples/gl/example_wireframe.py
get_wireframe
def get_wireframe(viewer, x, y, z, **kwargs): """Produce a compound object of paths implementing a wireframe. x, y, z are expected to be 2D arrays of points making up the mesh. """ # 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)
python
def get_wireframe(viewer, x, y, z, **kwargs): """Produce a compound object of paths implementing a wireframe. x, y, z are expected to be 2D arrays of points making up the mesh. """ # 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)
[ "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", "...
Produce a compound object of paths implementing a wireframe. x, y, z are expected to be 2D arrays of points making up the mesh.
[ "Produce", "a", "compound", "object", "of", "paths", "implementing", "a", "wireframe", ".", "x", "y", "z", "are", "expected", "to", "be", "2D", "arrays", "of", "points", "making", "up", "the", "mesh", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/gl/example_wireframe.py#L110-L128
train
25,055
ejeschke/ginga
ginga/util/iohelper.py
get_fileinfo
def get_fileinfo(filespec, cache_dir=None): """ Parse a file specification and return information about it. """ 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
python
def get_fileinfo(filespec, cache_dir=None): """ Parse a file specification and return information about it. """ 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
[ "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....
Parse a file specification and return information about it.
[ "Parse", "a", "file", "specification", "and", "return", "information", "about", "it", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/iohelper.py#L102-L167
train
25,056
ejeschke/ginga
ginga/util/iohelper.py
shorten_name
def shorten_name(name, char_limit, side='right'): """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. """ # 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
python
def shorten_name(name, char_limit, side='right'): """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. """ # 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
[ "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"...
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.
[ "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...
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/iohelper.py#L202-L230
train
25,057
ejeschke/ginga
ginga/misc/ParamSet.py
ParamSet.update_params
def update_params(self, param_d): """Update the attributes in self.obj that match the keys in `param_d`. """ for param in self.paramlst: if param.name in param_d: value = param_d[param.name] setattr(self.obj, param.name, value)
python
def update_params(self, param_d): """Update the attributes in self.obj that match the keys in `param_d`. """ for param in self.paramlst: if param.name in param_d: value = param_d[param.name] setattr(self.obj, param.name, value)
[ "def", "update_params", "(", "self", ",", "param_d", ")", ":", "for", "param", "in", "self", ".", "paramlst", ":", "if", "param", ".", "name", "in", "param_d", ":", "value", "=", "param_d", "[", "param", ".", "name", "]", "setattr", "(", "self", ".",...
Update the attributes in self.obj that match the keys in `param_d`.
[ "Update", "the", "attributes", "in", "self", ".", "obj", "that", "match", "the", "keys", "in", "param_d", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/ParamSet.py#L131-L138
train
25,058
ejeschke/ginga
ginga/util/colorramp.py
hue_sat_to_cmap
def hue_sat_to_cmap(hue, sat): """Mkae a color map from a hue and saturation value. """ 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
python
def hue_sat_to_cmap(hue, sat): """Mkae a color map from a hue and saturation value. """ 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
[ "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...
Mkae a color map from a hue and saturation value.
[ "Mkae", "a", "color", "map", "from", "a", "hue", "and", "saturation", "value", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/colorramp.py#L6-L21
train
25,059
ejeschke/ginga
ginga/misc/Bunch.py
threadSafeBunch.setitem
def setitem(self, key, value): """Maps dictionary keys to values for assignment. Called for dictionary style access with assignment. """ with self.lock: self.tbl[key] = value
python
def setitem(self, key, value): """Maps dictionary keys to values for assignment. Called for dictionary style access with assignment. """ with self.lock: self.tbl[key] = value
[ "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.
[ "Maps", "dictionary", "keys", "to", "values", "for", "assignment", ".", "Called", "for", "dictionary", "style", "access", "with", "assignment", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Bunch.py#L379-L384
train
25,060
ejeschke/ginga
ginga/misc/Bunch.py
threadSafeBunch.get
def get(self, key, alt=None): """If dictionary contains _key_ return the associated value, otherwise return _alt_. """ with self.lock: if key in self: return self.getitem(key) else: return alt
python
def get(self, key, alt=None): """If dictionary contains _key_ return the associated value, otherwise return _alt_. """ with self.lock: if key in self: return self.getitem(key) else: return alt
[ "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_.
[ "If", "dictionary", "contains", "_key_", "return", "the", "associated", "value", "otherwise", "return", "_alt_", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Bunch.py#L497-L506
train
25,061
ejeschke/ginga
ginga/misc/Bunch.py
threadSafeBunch.setdefault
def setdefault(self, key, 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. """ with self.lock: if key in self: return self.getitem(key) else: self.setitem(key, value) return value
python
def setdefault(self, key, 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. """ with self.lock: if key in self: return self.getitem(key) else: self.setitem(key, value) return value
[ "def", "setdefault", "(", "self", ",", "key", ",", "value", ")", ":", "with", "self", ".", "lock", ":", "if", "key", "in", "self", ":", "return", "self", ".", "getitem", "(", "key", ")", "else", ":", "self", ".", "setitem", "(", "key", ",", "valu...
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.
[ "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", ...
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Bunch.py#L508-L519
train
25,062
ejeschke/ginga
ginga/GingaPlugin.py
BasePlugin.help
def help(self): """Display help for the plugin.""" 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)
python
def help(self): """Display help for the plugin.""" 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)
[ "def", "help", "(", "self", ")", ":", "if", "not", "self", ".", "fv", ".", "gpmon", ".", "has_plugin", "(", "'WBrowser'", ")", ":", "self", ".", "_help_docstring", "(", ")", "return", "self", ".", "fv", ".", "start_global_plugin", "(", "'WBrowser'", ")...
Display help for the plugin.
[ "Display", "help", "for", "the", "plugin", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/GingaPlugin.py#L58-L70
train
25,063
ejeschke/ginga
ginga/GingaPlugin.py
LocalPlugin.modes_off
def modes_off(self): """Turn off any mode user may be in.""" bm = self.fitsimage.get_bindmap() bm.reset_mode(self.fitsimage)
python
def modes_off(self): """Turn off any mode user may be in.""" bm = self.fitsimage.get_bindmap() bm.reset_mode(self.fitsimage)
[ "def", "modes_off", "(", "self", ")", ":", "bm", "=", "self", ".", "fitsimage", ".", "get_bindmap", "(", ")", "bm", ".", "reset_mode", "(", "self", ".", "fitsimage", ")" ]
Turn off any mode user may be in.
[ "Turn", "off", "any", "mode", "user", "may", "be", "in", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/GingaPlugin.py#L100-L103
train
25,064
ejeschke/ginga
ginga/util/grc.py
_channel_proxy.load_np
def load_np(self, imname, data_np, imtype, header): """Display a numpy image buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. data_np : ndarray This should be at least a 2D Numpy array. imtype : str Image type--currently ignored. header : dict Fits header as a dictionary, or other keyword metadata. Returns ------- 0 Notes ----- * The "RC" plugin needs to be started in the viewer for this to work. """ # 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)
python
def load_np(self, imname, data_np, imtype, header): """Display a numpy image buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. data_np : ndarray This should be at least a 2D Numpy array. imtype : str Image type--currently ignored. header : dict Fits header as a dictionary, or other keyword metadata. Returns ------- 0 Notes ----- * The "RC" plugin needs to be started in the viewer for this to work. """ # 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)
[ "def", "load_np", "(", "self", ",", "imname", ",", "data_np", ",", "imtype", ",", "header", ")", ":", "# future: handle imtype", "load_buffer", "=", "self", ".", "_client", ".", "lookup_attr", "(", "'load_buffer'", ")", "return", "load_buffer", "(", "imname", ...
Display a numpy image buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. data_np : ndarray This should be at least a 2D Numpy array. imtype : str Image type--currently ignored. header : dict Fits header as a dictionary, or other keyword metadata. Returns ------- 0 Notes ----- * The "RC" plugin needs to be started in the viewer for this to work.
[ "Display", "a", "numpy", "image", "buffer", "in", "a", "remote", "Ginga", "reference", "viewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/grc.py#L60-L92
train
25,065
ejeschke/ginga
ginga/util/grc.py
_channel_proxy.load_hdu
def load_hdu(self, imname, hdulist, num_hdu): """Display an astropy.io.fits HDU in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. hdulist : `~astropy.io.fits.HDUList` This should be a valid HDUList loaded via the `astropy.io.fits` module. num_hdu : int or 2-tuple Number or key of the HDU to open from the `HDUList`. Returns ------- 0 Notes ----- * The "RC" plugin needs to be started in the viewer for this to work. """ 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, {})
python
def load_hdu(self, imname, hdulist, num_hdu): """Display an astropy.io.fits HDU in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. hdulist : `~astropy.io.fits.HDUList` This should be a valid HDUList loaded via the `astropy.io.fits` module. num_hdu : int or 2-tuple Number or key of the HDU to open from the `HDUList`. Returns ------- 0 Notes ----- * The "RC" plugin needs to be started in the viewer for this to work. """ 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, {})
[ "def", "load_hdu", "(", "self", ",", "imname", ",", "hdulist", ",", "num_hdu", ")", ":", "buf_io", "=", "BytesIO", "(", ")", "hdulist", ".", "writeto", "(", "buf_io", ")", "load_fits_buffer", "=", "self", ".", "_client", ".", "lookup_attr", "(", "'load_f...
Display an astropy.io.fits HDU in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. hdulist : `~astropy.io.fits.HDUList` This should be a valid HDUList loaded via the `astropy.io.fits` module. num_hdu : int or 2-tuple Number or key of the HDU to open from the `HDUList`. Returns ------- 0 Notes ----- * The "RC" plugin needs to be started in the viewer for this to work.
[ "Display", "an", "astropy", ".", "io", ".", "fits", "HDU", "in", "a", "remote", "Ginga", "reference", "viewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/grc.py#L94-L123
train
25,066
ejeschke/ginga
ginga/util/grc.py
_channel_proxy.load_fitsbuf
def load_fitsbuf(self, imname, fitsbuf, num_hdu): """Display a FITS file buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. chname : str Name of a channel in which to load the image. fitsbuf : str This should be a valid FITS file, read in as a complete buffer. num_hdu : int or 2-tuple Number or key of the HDU to open from the buffer. Returns ------- 0 Notes ----- * The "RC" plugin needs to be started in the viewer for this to work. """ load_fits_buffer = self._client_.lookup_attr('load_fits_buffer') return load_fits_buffer(imname, self._chname, Blob(fitsbuf), num_hdu, {})
python
def load_fitsbuf(self, imname, fitsbuf, num_hdu): """Display a FITS file buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. chname : str Name of a channel in which to load the image. fitsbuf : str This should be a valid FITS file, read in as a complete buffer. num_hdu : int or 2-tuple Number or key of the HDU to open from the buffer. Returns ------- 0 Notes ----- * The "RC" plugin needs to be started in the viewer for this to work. """ load_fits_buffer = self._client_.lookup_attr('load_fits_buffer') return load_fits_buffer(imname, self._chname, Blob(fitsbuf), num_hdu, {})
[ "def", "load_fitsbuf", "(", "self", ",", "imname", ",", "fitsbuf", ",", "num_hdu", ")", ":", "load_fits_buffer", "=", "self", ".", "_client_", ".", "lookup_attr", "(", "'load_fits_buffer'", ")", "return", "load_fits_buffer", "(", "imname", ",", "self", ".", ...
Display a FITS file buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. chname : str Name of a channel in which to load the image. fitsbuf : str This should be a valid FITS file, read in as a complete buffer. num_hdu : int or 2-tuple Number or key of the HDU to open from the buffer. Returns ------- 0 Notes ----- * The "RC" plugin needs to be started in the viewer for this to work.
[ "Display", "a", "FITS", "file", "buffer", "in", "a", "remote", "Ginga", "reference", "viewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/grc.py#L125-L154
train
25,067
ejeschke/ginga
ginga/tkw/ImageViewTk.py
ImageViewTk.set_widget
def set_widget(self, canvas): """Call this method with the Tkinter canvas that will be used for the display. """ 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)
python
def set_widget(self, canvas): """Call this method with the Tkinter canvas that will be used for the display. """ 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)
[ "def", "set_widget", "(", "self", ",", "canvas", ")", ":", "self", ".", "tkcanvas", "=", "canvas", "canvas", ".", "bind", "(", "\"<Configure>\"", ",", "self", ".", "_resize_cb", ")", "width", "=", "canvas", ".", "winfo_width", "(", ")", "height", "=", ...
Call this method with the Tkinter canvas that will be used for the display.
[ "Call", "this", "method", "with", "the", "Tkinter", "canvas", "that", "will", "be", "used", "for", "the", "display", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/tkw/ImageViewTk.py#L63-L81
train
25,068
ejeschke/ginga
ginga/mplw/transform.py
GingaAxes._set_lim_and_transforms
def _set_lim_and_transforms(self): """ This is called once when the plot is created to set up all the transforms for the data, text and grids. """ # 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
python
def _set_lim_and_transforms(self): """ This is called once when the plot is created to set up all the transforms for the data, text and grids. """ # 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
[ "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.", "#", "...
This is called once when the plot is created to set up all the transforms for the data, text and grids.
[ "This", "is", "called", "once", "when", "the", "plot", "is", "created", "to", "set", "up", "all", "the", "transforms", "for", "the", "data", "text", "and", "grids", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/mplw/transform.py#L46-L90
train
25,069
ejeschke/ginga
ginga/mplw/transform.py
GingaAxes.start_pan
def start_pan(self, x, y, button): """ Called when a pan operation has started. *x*, *y* are the mouse coordinates in display coords. button is the mouse button number: * 1: LEFT * 2: MIDDLE * 3: RIGHT .. note:: Intended to be overridden by new projection types. """ 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)
python
def start_pan(self, x, y, button): """ Called when a pan operation has started. *x*, *y* are the mouse coordinates in display coords. button is the mouse button number: * 1: LEFT * 2: MIDDLE * 3: RIGHT .. note:: Intended to be overridden by new projection types. """ 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)
[ "def", "start_pan", "(", "self", ",", "x", ",", "y", ",", "button", ")", ":", "bd", "=", "self", ".", "viewer", ".", "get_bindings", "(", ")", "data_x", ",", "data_y", "=", "self", ".", "viewer", ".", "get_data_xy", "(", "x", ",", "y", ")", "even...
Called when a pan operation has started. *x*, *y* are the mouse coordinates in display coords. button is the mouse button number: * 1: LEFT * 2: MIDDLE * 3: RIGHT .. note:: Intended to be overridden by new projection types.
[ "Called", "when", "a", "pan", "operation", "has", "started", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/mplw/transform.py#L142-L166
train
25,070
ejeschke/ginga
ginga/canvas/render.py
RendererBase.get_surface_as_bytes
def get_surface_as_bytes(self, order=None): """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. """ arr8 = self.get_surface_as_array(order=order) return arr8.tobytes(order='C')
python
def get_surface_as_bytes(self, order=None): """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. """ arr8 = self.get_surface_as_array(order=order) return arr8.tobytes(order='C')
[ "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.
[ "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", "....
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/render.py#L48-L54
train
25,071
ejeschke/ginga
ginga/canvas/render.py
RendererBase.reorder
def reorder(self, dst_order, arr, src_order=None): """Reorder the output array to match that needed by the viewer.""" 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
python
def reorder(self, dst_order, arr, src_order=None): """Reorder the output array to match that needed by the viewer.""" 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
[ "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", "=...
Reorder the output array to match that needed by the viewer.
[ "Reorder", "the", "output", "array", "to", "match", "that", "needed", "by", "the", "viewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/render.py#L107-L116
train
25,072
ejeschke/ginga
ginga/cmap.py
add_cmap
def add_cmap(name, clst): """Add a color map.""" 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)
python
def add_cmap(name, clst): """Add a color map.""" 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)
[ "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", ")", ...
Add a color map.
[ "Add", "a", "color", "map", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/cmap.py#L13250-L13256
train
25,073
ejeschke/ginga
ginga/cmap.py
get_names
def get_names(): """Get colormap names.""" res = list(cmaps.keys()) res = sorted(res, key=lambda s: s.lower()) return res
python
def get_names(): """Get colormap names.""" res = list(cmaps.keys()) res = sorted(res, key=lambda s: s.lower()) return res
[ "def", "get_names", "(", ")", ":", "res", "=", "list", "(", "cmaps", ".", "keys", "(", ")", ")", "res", "=", "sorted", "(", "res", ",", "key", "=", "lambda", "s", ":", "s", ".", "lower", "(", ")", ")", "return", "res" ]
Get colormap names.
[ "Get", "colormap", "names", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/cmap.py#L13272-L13276
train
25,074
ejeschke/ginga
ginga/cmap.py
matplotlib_to_ginga_cmap
def matplotlib_to_ginga_cmap(cm, name=None): """Convert matplotlib colormap to Ginga's.""" 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)
python
def matplotlib_to_ginga_cmap(cm, name=None): """Convert matplotlib colormap to Ginga's.""" 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)
[ "def", "matplotlib_to_ginga_cmap", "(", "cm", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "cm", ".", "name", "arr", "=", "cm", "(", "np", ".", "arange", "(", "0", ",", "min_cmap_len", ")", "/", "np", ".", "fl...
Convert matplotlib colormap to Ginga's.
[ "Convert", "matplotlib", "colormap", "to", "Ginga", "s", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/cmap.py#L13279-L13285
train
25,075
ejeschke/ginga
ginga/cmap.py
ginga_to_matplotlib_cmap
def ginga_to_matplotlib_cmap(cm, name=None): """Convert Ginga colormap to matplotlib's.""" 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
python
def ginga_to_matplotlib_cmap(cm, name=None): """Convert Ginga colormap to matplotlib's.""" 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
[ "def", "ginga_to_matplotlib_cmap", "(", "cm", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "cm", ".", "name", "from", "matplotlib", ".", "colors", "import", "ListedColormap", "carr", "=", "np", ".", "asarray", "(", ...
Convert Ginga colormap to matplotlib's.
[ "Convert", "Ginga", "colormap", "to", "matplotlib", "s", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/cmap.py#L13288-L13295
train
25,076
ejeschke/ginga
ginga/cmap.py
add_matplotlib_cmap
def add_matplotlib_cmap(cm, name=None): """Add a matplotlib colormap.""" global cmaps cmap = matplotlib_to_ginga_cmap(cm, name=name) cmaps[cmap.name] = cmap
python
def add_matplotlib_cmap(cm, name=None): """Add a matplotlib colormap.""" global cmaps cmap = matplotlib_to_ginga_cmap(cm, name=name) cmaps[cmap.name] = cmap
[ "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.
[ "Add", "a", "matplotlib", "colormap", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/cmap.py#L13298-L13302
train
25,077
ejeschke/ginga
ginga/cmap.py
add_matplotlib_cmaps
def add_matplotlib_cmaps(fail_on_import_error=True): """Add all matplotlib colormaps.""" 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)))
python
def add_matplotlib_cmaps(fail_on_import_error=True): """Add all matplotlib colormaps.""" 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)))
[ "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_er...
Add all matplotlib colormaps.
[ "Add", "all", "matplotlib", "colormaps", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/cmap.py#L13305-L13327
train
25,078
ejeschke/ginga
ginga/rv/plugins/Cuts.py
Cuts.add_legend
def add_legend(self): """Add or update Cuts plot legend.""" 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)
python
def add_legend(self): """Add or update Cuts plot legend.""" 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)
[ "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", "="...
Add or update Cuts plot legend.
[ "Add", "or", "update", "Cuts", "plot", "legend", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Cuts.py#L620-L625
train
25,079
ejeschke/ginga
ginga/rv/plugins/Cuts.py
Cuts.cut_at
def cut_at(self, cuttype): """Perform a cut at the last mouse position in the image. `cuttype` determines the type of cut made. """ 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()
python
def cut_at(self, cuttype): """Perform a cut at the last mouse position in the image. `cuttype` determines the type of cut made. """ 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()
[ "def", "cut_at", "(", "self", ",", "cuttype", ")", ":", "data_x", ",", "data_y", "=", "self", ".", "fitsimage", ".", "get_last_data_xy", "(", ")", "image", "=", "self", ".", "fitsimage", ".", "get_image", "(", ")", "wd", ",", "ht", "=", "image", ".",...
Perform a cut at the last mouse position in the image. `cuttype` determines the type of cut made.
[ "Perform", "a", "cut", "at", "the", "last", "mouse", "position", "in", "the", "image", ".", "cuttype", "determines", "the", "type", "of", "cut", "made", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Cuts.py#L915-L956
train
25,080
ejeschke/ginga
ginga/rv/plugins/Cuts.py
Cuts.width_radius_changed_cb
def width_radius_changed_cb(self, widget, val): """Callback executed when the Width radius is changed.""" self.width_radius = val self.redraw_cuts() self.replot_all() return True
python
def width_radius_changed_cb(self, widget, val): """Callback executed when the Width radius is changed.""" self.width_radius = val self.redraw_cuts() self.replot_all() return True
[ "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.
[ "Callback", "executed", "when", "the", "Width", "radius", "is", "changed", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Cuts.py#L1021-L1026
train
25,081
ejeschke/ginga
ginga/rv/plugins/Cuts.py
Cuts.save_cb
def save_cb(self, mode): """Save image, figure, and plot data arrays.""" # 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)
python
def save_cb(self, mode): """Save image, figure, and plot data arrays.""" # 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)
[ "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", ")",...
Save image, figure, and plot data arrays.
[ "Save", "image", "figure", "and", "plot", "data", "arrays", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Cuts.py#L1034-L1061
train
25,082
ejeschke/ginga
ginga/rv/plugins/Pan.py
Pan.zoom_cb
def zoom_cb(self, fitsimage, event): """Zoom event in the pan window. Just zoom the channel viewer. """ chviewer = self.fv.getfocus_viewer() bd = chviewer.get_bindings() if hasattr(bd, 'sc_zoom'): return bd.sc_zoom(chviewer, event) return False
python
def zoom_cb(self, fitsimage, event): """Zoom event in the pan window. Just zoom the channel viewer. """ chviewer = self.fv.getfocus_viewer() bd = chviewer.get_bindings() if hasattr(bd, 'sc_zoom'): return bd.sc_zoom(chviewer, event) return False
[ "def", "zoom_cb", "(", "self", ",", "fitsimage", ",", "event", ")", ":", "chviewer", "=", "self", ".", "fv", ".", "getfocus_viewer", "(", ")", "bd", "=", "chviewer", ".", "get_bindings", "(", ")", "if", "hasattr", "(", "bd", ",", "'sc_zoom'", ")", ":...
Zoom event in the pan window. Just zoom the channel viewer.
[ "Zoom", "event", "in", "the", "pan", "window", ".", "Just", "zoom", "the", "channel", "viewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Pan.py#L398-L407
train
25,083
ejeschke/ginga
ginga/rv/plugins/Pan.py
Pan.zoom_pinch_cb
def zoom_pinch_cb(self, fitsimage, event): """Pinch event in the pan window. Just zoom the channel viewer. """ chviewer = self.fv.getfocus_viewer() bd = chviewer.get_bindings() if hasattr(bd, 'pi_zoom'): return bd.pi_zoom(chviewer, event) return False
python
def zoom_pinch_cb(self, fitsimage, event): """Pinch event in the pan window. Just zoom the channel viewer. """ chviewer = self.fv.getfocus_viewer() bd = chviewer.get_bindings() if hasattr(bd, 'pi_zoom'): return bd.pi_zoom(chviewer, event) return False
[ "def", "zoom_pinch_cb", "(", "self", ",", "fitsimage", ",", "event", ")", ":", "chviewer", "=", "self", ".", "fv", ".", "getfocus_viewer", "(", ")", "bd", "=", "chviewer", ".", "get_bindings", "(", ")", "if", "hasattr", "(", "bd", ",", "'pi_zoom'", ")"...
Pinch event in the pan window. Just zoom the channel viewer.
[ "Pinch", "event", "in", "the", "pan", "window", ".", "Just", "zoom", "the", "channel", "viewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Pan.py#L409-L418
train
25,084
ejeschke/ginga
ginga/rv/plugins/Pan.py
Pan.pan_pan_cb
def pan_pan_cb(self, fitsimage, event): """Pan event in the pan window. Just pan the channel viewer. """ chviewer = self.fv.getfocus_viewer() bd = chviewer.get_bindings() if hasattr(bd, 'pa_pan'): return bd.pa_pan(chviewer, event) return False
python
def pan_pan_cb(self, fitsimage, event): """Pan event in the pan window. Just pan the channel viewer. """ chviewer = self.fv.getfocus_viewer() bd = chviewer.get_bindings() if hasattr(bd, 'pa_pan'): return bd.pa_pan(chviewer, event) return False
[ "def", "pan_pan_cb", "(", "self", ",", "fitsimage", ",", "event", ")", ":", "chviewer", "=", "self", ".", "fv", ".", "getfocus_viewer", "(", ")", "bd", "=", "chviewer", ".", "get_bindings", "(", ")", "if", "hasattr", "(", "bd", ",", "'pa_pan'", ")", ...
Pan event in the pan window. Just pan the channel viewer.
[ "Pan", "event", "in", "the", "pan", "window", ".", "Just", "pan", "the", "channel", "viewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Pan.py#L420-L429
train
25,085
ejeschke/ginga
ginga/web/pgw/ImageViewPg.py
ImageViewPg.set_widget
def set_widget(self, canvas_w): """Call this method with the widget that will be used for the display. """ self.logger.debug("set widget canvas_w=%s" % canvas_w) self.pgcanvas = canvas_w
python
def set_widget(self, canvas_w): """Call this method with the widget that will be used for the display. """ self.logger.debug("set widget canvas_w=%s" % canvas_w) self.pgcanvas = canvas_w
[ "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.
[ "Call", "this", "method", "with", "the", "widget", "that", "will", "be", "used", "for", "the", "display", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ImageViewPg.py#L63-L68
train
25,086
python-bugzilla/python-bugzilla
setup.py
RPMCommand.run
def run(self): """ Run sdist, then 'rpmbuild' the tar.gz """ 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 .")
python
def run(self): """ Run sdist, then 'rpmbuild' the tar.gz """ 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 .")
[ "def", "run", "(", "self", ")", ":", "os", ".", "system", "(", "\"cp python-bugzilla.spec /tmp\"", ")", "try", ":", "os", ".", "system", "(", "\"rm -rf python-bugzilla-%s\"", "%", "get_version", "(", ")", ")", "self", ".", "run_command", "(", "'sdist'", ")",...
Run sdist, then 'rpmbuild' the tar.gz
[ "Run", "sdist", "then", "rpmbuild", "the", "tar", ".", "gz" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/setup.py#L86-L97
train
25,087
python-bugzilla/python-bugzilla
bugzilla/transport.py
_RequestsTransport.parse_response
def parse_response(self, response): """ Parse XMLRPC response """ parser, unmarshaller = self.getparser() parser.feed(response.text.encode('utf-8')) parser.close() return unmarshaller.close()
python
def parse_response(self, response): """ Parse XMLRPC response """ parser, unmarshaller = self.getparser() parser.feed(response.text.encode('utf-8')) parser.close() return unmarshaller.close()
[ "def", "parse_response", "(", "self", ",", "response", ")", ":", "parser", ",", "unmarshaller", "=", "self", ".", "getparser", "(", ")", "parser", ".", "feed", "(", "response", ".", "text", ".", "encode", "(", "'utf-8'", ")", ")", "parser", ".", "close...
Parse XMLRPC response
[ "Parse", "XMLRPC", "response" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/transport.py#L147-L154
train
25,088
python-bugzilla/python-bugzilla
bugzilla/transport.py
_RequestsTransport._request_helper
def _request_helper(self, url, request_body): """ A helper method to assist in making a request and provide a parsed response. """ 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
python
def _request_helper(self, url, request_body): """ A helper method to assist in making a request and provide a parsed response. """ 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
[ "def", "_request_helper", "(", "self", ",", "url", ",", "request_body", ")", ":", "response", "=", "None", "# pylint: disable=try-except-raise", "try", ":", "response", "=", "self", ".", "session", ".", "post", "(", "url", ",", "data", "=", "request_body", "...
A helper method to assist in making a request and provide a parsed response.
[ "A", "helper", "method", "to", "assist", "in", "making", "a", "request", "and", "provide", "a", "parsed", "response", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/transport.py#L156-L193
train
25,089
python-bugzilla/python-bugzilla
bugzilla/_cli.py
open_without_clobber
def open_without_clobber(name, *args): """ 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. """ 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
python
def open_without_clobber(name, *args): """ 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. """ 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
[ "def", "open_without_clobber", "(", "name", ",", "*", "args", ")", ":", "fd", "=", "None", "count", "=", "1", "orig_name", "=", "name", "while", "fd", "is", "None", ":", "try", ":", "fd", "=", "os", ".", "open", "(", "name", ",", "os", ".", "O_CR...
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.
[ "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", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/_cli.py#L77-L97
train
25,090
python-bugzilla/python-bugzilla
bugzilla/_cli.py
_do_info
def _do_info(bz, opt): """ Handle the 'info' subcommand """ # 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'])))
python
def _do_info(bz, opt): """ Handle the 'info' subcommand """ # 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'])))
[ "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", ...
Handle the 'info' subcommand
[ "Handle", "the", "info", "subcommand" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/_cli.py#L600-L652
train
25,091
python-bugzilla/python-bugzilla
bugzilla/_cli.py
_make_bz_instance
def _make_bz_instance(opt): """ Build the Bugzilla instance we will use """ 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
python
def _make_bz_instance(opt): """ Build the Bugzilla instance we will use """ 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
[ "def", "_make_bz_instance", "(", "opt", ")", ":", "if", "opt", ".", "bztype", "!=", "'auto'", ":", "log", ".", "info", "(", "\"Explicit --bztype is no longer supported, ignoring\"", ")", "cookiefile", "=", "None", "tokenfile", "=", "None", "use_creds", "=", "Fal...
Build the Bugzilla instance we will use
[ "Build", "the", "Bugzilla", "instance", "we", "will", "use" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/_cli.py#L1030-L1052
train
25,092
python-bugzilla/python-bugzilla
bugzilla/_cli.py
_handle_login
def _handle_login(opt, action, bz): """ Handle all login related bits """ 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)
python
def _handle_login(opt, action, bz): """ Handle all login related bits """ 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)
[ "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"...
Handle all login related bits
[ "Handle", "all", "login", "related", "bits" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/_cli.py#L1055-L1087
train
25,093
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.fix_url
def fix_url(url): """ Turn passed url into a bugzilla XMLRPC web 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
python
def fix_url(url): """ Turn passed url into a bugzilla XMLRPC web 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
[ "def", "fix_url", "(", "url", ")", ":", "if", "'://'", "not", "in", "url", ":", "log", ".", "debug", "(", "'No scheme given for url, assuming https'", ")", "url", "=", "'https://'", "+", "url", "if", "url", ".", "count", "(", "'/'", ")", "<", "3", ":",...
Turn passed url into a bugzilla XMLRPC web url
[ "Turn", "passed", "url", "into", "a", "bugzilla", "XMLRPC", "web", "url" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L215-L225
train
25,094
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._init_class_from_url
def _init_class_from_url(self): """ Detect if we should use RHBugzilla class, and if so, set it """ 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
python
def _init_class_from_url(self): """ Detect if we should use RHBugzilla class, and if so, set it """ 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
[ "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",...
Detect if we should use RHBugzilla class, and if so, set it
[ "Detect", "if", "we", "should", "use", "RHBugzilla", "class", "and", "if", "so", "set", "it" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L310-L335
train
25,095
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._login
def _login(self, user, password, restrict_login=None): """ Backend login method for Bugzilla3 """ payload = {'login': user, 'password': password} if restrict_login: payload['restrict_login'] = True return self._proxy.User.login(payload)
python
def _login(self, user, password, restrict_login=None): """ Backend login method for Bugzilla3 """ payload = {'login': user, 'password': password} if restrict_login: payload['restrict_login'] = True return self._proxy.User.login(payload)
[ "def", "_login", "(", "self", ",", "user", ",", "password", ",", "restrict_login", "=", "None", ")", ":", "payload", "=", "{", "'login'", ":", "user", ",", "'password'", ":", "password", "}", "if", "restrict_login", ":", "payload", "[", "'restrict_login'",...
Backend login method for Bugzilla3
[ "Backend", "login", "method", "for", "Bugzilla3" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L565-L573
train
25,096
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.login
def login(self, user=None, password=None, restrict_login=None): """ 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. If user is not set, the value of Bugzilla.user will be used. If *that* is not set, ValueError will be raised. If login fails, BugzillaError will be raised. The login session can be restricted to current user IP address with restrict_login argument. (Bugzilla 4.4+) This method will be called implicitly at the end of connect() if user and password are both set. So under most circumstances you won't need to call this yourself. """ 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))
python
def login(self, user=None, password=None, restrict_login=None): """ 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. If user is not set, the value of Bugzilla.user will be used. If *that* is not set, ValueError will be raised. If login fails, BugzillaError will be raised. The login session can be restricted to current user IP address with restrict_login argument. (Bugzilla 4.4+) This method will be called implicitly at the end of connect() if user and password are both set. So under most circumstances you won't need to call this yourself. """ 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))
[ "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", "...
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. If user is not set, the value of Bugzilla.user will be used. If *that* is not set, ValueError will be raised. If login fails, BugzillaError will be raised. The login session can be restricted to current user IP address with restrict_login argument. (Bugzilla 4.4+) This method will be called implicitly at the end of connect() if user and password are both set. So under most circumstances you won't need to call this yourself.
[ "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", ...
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L581-L621
train
25,097
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.interactive_login
def interactive_login(self, user=None, password=None, force=False, restrict_login=None): """ Helper method to handle login for this bugzilla instance. :param user: bugzilla username. If not specified, prompt for it. :param password: bugzilla password. If not specified, prompt for it. :param force: Unused :param restrict_login: restricts session to IP address """ 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.')
python
def interactive_login(self, user=None, password=None, force=False, restrict_login=None): """ Helper method to handle login for this bugzilla instance. :param user: bugzilla username. If not specified, prompt for it. :param password: bugzilla password. If not specified, prompt for it. :param force: Unused :param restrict_login: restricts session to IP address """ 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.')
[ "def", "interactive_login", "(", "self", ",", "user", "=", "None", ",", "password", "=", "None", ",", "force", "=", "False", ",", "restrict_login", "=", "None", ")", ":", "ignore", "=", "force", "log", ".", "debug", "(", "'Calling interactive_login'", ")",...
Helper method to handle login for this bugzilla instance. :param user: bugzilla username. If not specified, prompt for it. :param password: bugzilla password. If not specified, prompt for it. :param force: Unused :param restrict_login: restricts session to IP address
[ "Helper", "method", "to", "handle", "login", "for", "this", "bugzilla", "instance", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L623-L645
train
25,098
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.logout
def logout(self): """ Log out of bugzilla. Drops server connection and user info, and destroys authentication cookies. """ self._logout() self.disconnect() self.user = '' self.password = ''
python
def logout(self): """ Log out of bugzilla. Drops server connection and user info, and destroys authentication cookies. """ self._logout() self.disconnect() self.user = '' self.password = ''
[ "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.
[ "Log", "out", "of", "bugzilla", ".", "Drops", "server", "connection", "and", "user", "info", "and", "destroys", "authentication", "cookies", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L647-L655
train
25,099