id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,500
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): 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
26,501
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): 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
26,502
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): 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
26,503
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): 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
26,504
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): # 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
26,505
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): # 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
26,506
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): # 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
26,507
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): 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
26,508
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): 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
26,509
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): 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
26,510
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): 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
26,511
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): 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
26,512
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): # 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
26,513
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): 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
26,514
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'): # 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
26,515
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): 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
26,516
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): 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
26,517
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): 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
26,518
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): 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
26,519
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): 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
26,520
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): 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
26,521
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): 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
26,522
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): # 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
26,523
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): 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
26,524
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): 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
26,525
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): 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
26,526
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): # 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
26,527
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): 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
26,528
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): 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
26,529
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): 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
26,530
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): 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
26,531
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(): 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
26,532
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): 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
26,533
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): 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
26,534
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): 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
26,535
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): 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
26,536
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): 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
26,537
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): 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
26,538
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): 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
26,539
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): # 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
26,540
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): 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
26,541
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): 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
26,542
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): 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
26,543
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): 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
26,544
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): 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
26,545
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): 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
26,546
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): 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
26,547
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): 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
26,548
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): # 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
26,549
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): 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
26,550
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): 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
26,551
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): 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
26,552
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): 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
26,553
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): 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
26,554
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): 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
26,555
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): 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
26,556
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): 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
26,557
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.logged_in
def logged_in(self): """ This is True if this instance is logged in else False. We test if this session is authenticated by calling the User.get() XMLRPC method with ids set. Logged-out users cannot pass the 'ids' parameter and will result in a 505 error. If we tried to login with a token, but the token was incorrect or expired, the server returns a 32000 error. For Bugzilla 5 and later, a new method, User.valid_login is available to test the validity of the token. However, this will require that the username be cached along with the token in order to work effectively in all scenarios and is not currently used. For more information, refer to the following url. http://bugzilla.readthedocs.org/en/latest/api/core/v1/user.html#valid-login """ try: self._proxy.User.get({'ids': []}) return True except Fault as e: if e.faultCode == 505 or e.faultCode == 32000: return False raise e
python
def logged_in(self): try: self._proxy.User.get({'ids': []}) return True except Fault as e: if e.faultCode == 505 or e.faultCode == 32000: return False raise e
[ "def", "logged_in", "(", "self", ")", ":", "try", ":", "self", ".", "_proxy", ".", "User", ".", "get", "(", "{", "'ids'", ":", "[", "]", "}", ")", "return", "True", "except", "Fault", "as", "e", ":", "if", "e", ".", "faultCode", "==", "505", "o...
This is True if this instance is logged in else False. We test if this session is authenticated by calling the User.get() XMLRPC method with ids set. Logged-out users cannot pass the 'ids' parameter and will result in a 505 error. If we tried to login with a token, but the token was incorrect or expired, the server returns a 32000 error. For Bugzilla 5 and later, a new method, User.valid_login is available to test the validity of the token. However, this will require that the username be cached along with the token in order to work effectively in all scenarios and is not currently used. For more information, refer to the following url. http://bugzilla.readthedocs.org/en/latest/api/core/v1/user.html#valid-login
[ "This", "is", "True", "if", "this", "instance", "is", "logged", "in", "else", "False", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L658-L682
26,558
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._getbugfields
def _getbugfields(self): """ Get the list of valid fields for Bug objects """ r = self._proxy.Bug.fields({'include_fields': ['name']}) return [f['name'] for f in r['fields']]
python
def _getbugfields(self): r = self._proxy.Bug.fields({'include_fields': ['name']}) return [f['name'] for f in r['fields']]
[ "def", "_getbugfields", "(", "self", ")", ":", "r", "=", "self", ".", "_proxy", ".", "Bug", ".", "fields", "(", "{", "'include_fields'", ":", "[", "'name'", "]", "}", ")", "return", "[", "f", "[", "'name'", "]", "for", "f", "in", "r", "[", "'fiel...
Get the list of valid fields for Bug objects
[ "Get", "the", "list", "of", "valid", "fields", "for", "Bug", "objects" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L689-L694
26,559
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getbugfields
def getbugfields(self, force_refresh=False): """ Calls getBugFields, which returns a list of fields in each bug for this bugzilla instance. This can be used to set the list of attrs on the Bug object. """ if force_refresh or not self._cache.bugfields: log.debug("Refreshing bugfields") self._cache.bugfields = self._getbugfields() self._cache.bugfields.sort() log.debug("bugfields = %s", self._cache.bugfields) return self._cache.bugfields
python
def getbugfields(self, force_refresh=False): if force_refresh or not self._cache.bugfields: log.debug("Refreshing bugfields") self._cache.bugfields = self._getbugfields() self._cache.bugfields.sort() log.debug("bugfields = %s", self._cache.bugfields) return self._cache.bugfields
[ "def", "getbugfields", "(", "self", ",", "force_refresh", "=", "False", ")", ":", "if", "force_refresh", "or", "not", "self", ".", "_cache", ".", "bugfields", ":", "log", ".", "debug", "(", "\"Refreshing bugfields\"", ")", "self", ".", "_cache", ".", "bugf...
Calls getBugFields, which returns a list of fields in each bug for this bugzilla instance. This can be used to set the list of attrs on the Bug object.
[ "Calls", "getBugFields", "which", "returns", "a", "list", "of", "fields", "in", "each", "bug", "for", "this", "bugzilla", "instance", ".", "This", "can", "be", "used", "to", "set", "the", "list", "of", "attrs", "on", "the", "Bug", "object", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L696-L708
26,560
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.refresh_products
def refresh_products(self, **kwargs): """ Refresh a product's cached info. Basically calls product_get with the passed arguments, and tries to intelligently update our product cache. For example, if we already have cached info for product=foo, and you pass in names=["bar", "baz"], the new cache will have info for products foo, bar, baz. Individual product fields are also updated. """ for product in self.product_get(**kwargs): updated = False for current in self._cache.products[:]: if (current.get("id", -1) != product.get("id", -2) and current.get("name", -1) != product.get("name", -2)): continue _nested_update(current, product) updated = True break if not updated: self._cache.products.append(product)
python
def refresh_products(self, **kwargs): for product in self.product_get(**kwargs): updated = False for current in self._cache.products[:]: if (current.get("id", -1) != product.get("id", -2) and current.get("name", -1) != product.get("name", -2)): continue _nested_update(current, product) updated = True break if not updated: self._cache.products.append(product)
[ "def", "refresh_products", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "product", "in", "self", ".", "product_get", "(", "*", "*", "kwargs", ")", ":", "updated", "=", "False", "for", "current", "in", "self", ".", "_cache", ".", "products", ...
Refresh a product's cached info. Basically calls product_get with the passed arguments, and tries to intelligently update our product cache. For example, if we already have cached info for product=foo, and you pass in names=["bar", "baz"], the new cache will have info for products foo, bar, baz. Individual product fields are also updated.
[ "Refresh", "a", "product", "s", "cached", "info", ".", "Basically", "calls", "product_get", "with", "the", "passed", "arguments", "and", "tries", "to", "intelligently", "update", "our", "product", "cache", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L765-L787
26,561
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getproducts
def getproducts(self, force_refresh=False, **kwargs): """ Query all products and return the raw dict info. Takes all the same arguments as product_get. On first invocation this will contact bugzilla and internally cache the results. Subsequent getproducts calls or accesses to self.products will return this cached data only. :param force_refresh: force refreshing via refresh_products() """ if force_refresh or not self._cache.products: self.refresh_products(**kwargs) return self._cache.products
python
def getproducts(self, force_refresh=False, **kwargs): if force_refresh or not self._cache.products: self.refresh_products(**kwargs) return self._cache.products
[ "def", "getproducts", "(", "self", ",", "force_refresh", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "force_refresh", "or", "not", "self", ".", "_cache", ".", "products", ":", "self", ".", "refresh_products", "(", "*", "*", "kwargs", ")", "r...
Query all products and return the raw dict info. Takes all the same arguments as product_get. On first invocation this will contact bugzilla and internally cache the results. Subsequent getproducts calls or accesses to self.products will return this cached data only. :param force_refresh: force refreshing via refresh_products()
[ "Query", "all", "products", "and", "return", "the", "raw", "dict", "info", ".", "Takes", "all", "the", "same", "arguments", "as", "product_get", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L789-L802
26,562
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getcomponentdetails
def getcomponentdetails(self, product, component, force_refresh=False): """ Helper for accessing a single component's info. This is a wrapper around getcomponentsdetails, see that for explanation """ d = self.getcomponentsdetails(product, force_refresh) return d[component]
python
def getcomponentdetails(self, product, component, force_refresh=False): d = self.getcomponentsdetails(product, force_refresh) return d[component]
[ "def", "getcomponentdetails", "(", "self", ",", "product", ",", "component", ",", "force_refresh", "=", "False", ")", ":", "d", "=", "self", ".", "getcomponentsdetails", "(", "product", ",", "force_refresh", ")", "return", "d", "[", "component", "]" ]
Helper for accessing a single component's info. This is a wrapper around getcomponentsdetails, see that for explanation
[ "Helper", "for", "accessing", "a", "single", "component", "s", "info", ".", "This", "is", "a", "wrapper", "around", "getcomponentsdetails", "see", "that", "for", "explanation" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L851-L857
26,563
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getcomponents
def getcomponents(self, product, force_refresh=False): """ Return a list of component names for the passed product. This can be implemented with Product.get, but behind the scenes it uses Bug.legal_values. Reason being that on bugzilla instances with tons of components, like bugzilla.redhat.com Product=Fedora for example, there's a 10x speed difference even with properly limited Product.get calls. On first invocation the value is cached, and subsequent calls will return the cached data. :param force_refresh: Force refreshing the cache, and return the new data """ proddict = self._lookup_product_in_cache(product) product_id = proddict.get("id", None) if (force_refresh or product_id is None or product_id not in self._cache.component_names): self.refresh_products(names=[product], include_fields=["name", "id"]) proddict = self._lookup_product_in_cache(product) if "id" not in proddict: raise BugzillaError("Product '%s' not found" % product) product_id = proddict["id"] opts = {'product_id': product_id, 'field': 'component'} names = self._proxy.Bug.legal_values(opts)["values"] self._cache.component_names[product_id] = names return self._cache.component_names[product_id]
python
def getcomponents(self, product, force_refresh=False): proddict = self._lookup_product_in_cache(product) product_id = proddict.get("id", None) if (force_refresh or product_id is None or product_id not in self._cache.component_names): self.refresh_products(names=[product], include_fields=["name", "id"]) proddict = self._lookup_product_in_cache(product) if "id" not in proddict: raise BugzillaError("Product '%s' not found" % product) product_id = proddict["id"] opts = {'product_id': product_id, 'field': 'component'} names = self._proxy.Bug.legal_values(opts)["values"] self._cache.component_names[product_id] = names return self._cache.component_names[product_id]
[ "def", "getcomponents", "(", "self", ",", "product", ",", "force_refresh", "=", "False", ")", ":", "proddict", "=", "self", ".", "_lookup_product_in_cache", "(", "product", ")", "product_id", "=", "proddict", ".", "get", "(", "\"id\"", ",", "None", ")", "i...
Return a list of component names for the passed product. This can be implemented with Product.get, but behind the scenes it uses Bug.legal_values. Reason being that on bugzilla instances with tons of components, like bugzilla.redhat.com Product=Fedora for example, there's a 10x speed difference even with properly limited Product.get calls. On first invocation the value is cached, and subsequent calls will return the cached data. :param force_refresh: Force refreshing the cache, and return the new data
[ "Return", "a", "list", "of", "component", "names", "for", "the", "passed", "product", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L859-L892
26,564
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._process_include_fields
def _process_include_fields(self, include_fields, exclude_fields, extra_fields): """ Internal helper to process include_fields lists """ def _convert_fields(_in): if not _in: return _in for newname, oldname in self._get_api_aliases(): if oldname in _in: _in.remove(oldname) if newname not in _in: _in.append(newname) return _in ret = {} if self._check_version(4, 0): if include_fields: include_fields = _convert_fields(include_fields) if "id" not in include_fields: include_fields.append("id") ret["include_fields"] = include_fields if exclude_fields: exclude_fields = _convert_fields(exclude_fields) ret["exclude_fields"] = exclude_fields if self._supports_getbug_extra_fields: if extra_fields: ret["extra_fields"] = _convert_fields(extra_fields) return ret
python
def _process_include_fields(self, include_fields, exclude_fields, extra_fields): def _convert_fields(_in): if not _in: return _in for newname, oldname in self._get_api_aliases(): if oldname in _in: _in.remove(oldname) if newname not in _in: _in.append(newname) return _in ret = {} if self._check_version(4, 0): if include_fields: include_fields = _convert_fields(include_fields) if "id" not in include_fields: include_fields.append("id") ret["include_fields"] = include_fields if exclude_fields: exclude_fields = _convert_fields(exclude_fields) ret["exclude_fields"] = exclude_fields if self._supports_getbug_extra_fields: if extra_fields: ret["extra_fields"] = _convert_fields(extra_fields) return ret
[ "def", "_process_include_fields", "(", "self", ",", "include_fields", ",", "exclude_fields", ",", "extra_fields", ")", ":", "def", "_convert_fields", "(", "_in", ")", ":", "if", "not", "_in", ":", "return", "_in", "for", "newname", ",", "oldname", "in", "sel...
Internal helper to process include_fields lists
[ "Internal", "helper", "to", "process", "include_fields", "lists" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L958-L987
26,565
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._getbugs
def _getbugs(self, idlist, permissive, include_fields=None, exclude_fields=None, extra_fields=None): """ Return a list of dicts of full bug info for each given bug id. bug ids that couldn't be found will return None instead of a dict. """ oldidlist = idlist idlist = [] for i in oldidlist: try: idlist.append(int(i)) except ValueError: # String aliases can be passed as well idlist.append(i) extra_fields = self._listify(extra_fields or []) extra_fields += self._getbug_extra_fields getbugdata = {"ids": idlist} if permissive: getbugdata["permissive"] = 1 getbugdata.update(self._process_include_fields( include_fields, exclude_fields, extra_fields)) r = self._proxy.Bug.get(getbugdata) if self._check_version(4, 0): bugdict = dict([(b['id'], b) for b in r['bugs']]) else: bugdict = dict([(b['id'], b['internals']) for b in r['bugs']]) ret = [] for i in idlist: found = None if i in bugdict: found = bugdict[i] else: # Need to map an alias for valdict in bugdict.values(): if i in self._listify(valdict.get("alias", None)): found = valdict break ret.append(found) return ret
python
def _getbugs(self, idlist, permissive, include_fields=None, exclude_fields=None, extra_fields=None): oldidlist = idlist idlist = [] for i in oldidlist: try: idlist.append(int(i)) except ValueError: # String aliases can be passed as well idlist.append(i) extra_fields = self._listify(extra_fields or []) extra_fields += self._getbug_extra_fields getbugdata = {"ids": idlist} if permissive: getbugdata["permissive"] = 1 getbugdata.update(self._process_include_fields( include_fields, exclude_fields, extra_fields)) r = self._proxy.Bug.get(getbugdata) if self._check_version(4, 0): bugdict = dict([(b['id'], b) for b in r['bugs']]) else: bugdict = dict([(b['id'], b['internals']) for b in r['bugs']]) ret = [] for i in idlist: found = None if i in bugdict: found = bugdict[i] else: # Need to map an alias for valdict in bugdict.values(): if i in self._listify(valdict.get("alias", None)): found = valdict break ret.append(found) return ret
[ "def", "_getbugs", "(", "self", ",", "idlist", ",", "permissive", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "extra_fields", "=", "None", ")", ":", "oldidlist", "=", "idlist", "idlist", "=", "[", "]", "for", "i", "in", ...
Return a list of dicts of full bug info for each given bug id. bug ids that couldn't be found will return None instead of a dict.
[ "Return", "a", "list", "of", "dicts", "of", "full", "bug", "info", "for", "each", "given", "bug", "id", ".", "bug", "ids", "that", "couldn", "t", "be", "found", "will", "return", "None", "instead", "of", "a", "dict", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1010-L1056
26,566
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._getbug
def _getbug(self, objid, **kwargs): """ Thin wrapper around _getbugs to handle the slight argument tweaks for fetching a single bug. The main bit is permissive=False, which will tell bugzilla to raise an explicit error if we can't fetch that bug. This logic is called from Bug() too """ return self._getbugs([objid], permissive=False, **kwargs)[0]
python
def _getbug(self, objid, **kwargs): return self._getbugs([objid], permissive=False, **kwargs)[0]
[ "def", "_getbug", "(", "self", ",", "objid", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_getbugs", "(", "[", "objid", "]", ",", "permissive", "=", "False", ",", "*", "*", "kwargs", ")", "[", "0", "]" ]
Thin wrapper around _getbugs to handle the slight argument tweaks for fetching a single bug. The main bit is permissive=False, which will tell bugzilla to raise an explicit error if we can't fetch that bug. This logic is called from Bug() too
[ "Thin", "wrapper", "around", "_getbugs", "to", "handle", "the", "slight", "argument", "tweaks", "for", "fetching", "a", "single", "bug", ".", "The", "main", "bit", "is", "permissive", "=", "False", "which", "will", "tell", "bugzilla", "to", "raise", "an", ...
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1058-L1067
26,567
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getbug
def getbug(self, objid, include_fields=None, exclude_fields=None, extra_fields=None): """ Return a Bug object with the full complement of bug data already loaded. """ data = self._getbug(objid, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields) return Bug(self, dict=data, autorefresh=self.bug_autorefresh)
python
def getbug(self, objid, include_fields=None, exclude_fields=None, extra_fields=None): data = self._getbug(objid, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields) return Bug(self, dict=data, autorefresh=self.bug_autorefresh)
[ "def", "getbug", "(", "self", ",", "objid", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "extra_fields", "=", "None", ")", ":", "data", "=", "self", ".", "_getbug", "(", "objid", ",", "include_fields", "=", "include_fields",...
Return a Bug object with the full complement of bug data already loaded.
[ "Return", "a", "Bug", "object", "with", "the", "full", "complement", "of", "bug", "data", "already", "loaded", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1069-L1078
26,568
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getbugs
def getbugs(self, idlist, include_fields=None, exclude_fields=None, extra_fields=None, permissive=True): """ Return a list of Bug objects with the full complement of bug data already loaded. If there's a problem getting the data for a given id, the corresponding item in the returned list will be None. """ data = self._getbugs(idlist, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields, permissive=permissive) return [(b and Bug(self, dict=b, autorefresh=self.bug_autorefresh)) or None for b in data]
python
def getbugs(self, idlist, include_fields=None, exclude_fields=None, extra_fields=None, permissive=True): data = self._getbugs(idlist, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields, permissive=permissive) return [(b and Bug(self, dict=b, autorefresh=self.bug_autorefresh)) or None for b in data]
[ "def", "getbugs", "(", "self", ",", "idlist", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "extra_fields", "=", "None", ",", "permissive", "=", "True", ")", ":", "data", "=", "self", ".", "_getbugs", "(", "idlist", ",", ...
Return a list of Bug objects with the full complement of bug data already loaded. If there's a problem getting the data for a given id, the corresponding item in the returned list will be None.
[ "Return", "a", "list", "of", "Bug", "objects", "with", "the", "full", "complement", "of", "bug", "data", "already", "loaded", ".", "If", "there", "s", "a", "problem", "getting", "the", "data", "for", "a", "given", "id", "the", "corresponding", "item", "i...
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1080-L1093
26,569
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.update_tags
def update_tags(self, idlist, tags_add=None, tags_remove=None): """ Updates the 'tags' field for a bug. """ tags = {} if tags_add: tags["add"] = self._listify(tags_add) if tags_remove: tags["remove"] = self._listify(tags_remove) d = { "ids": self._listify(idlist), "tags": tags, } return self._proxy.Bug.update_tags(d)
python
def update_tags(self, idlist, tags_add=None, tags_remove=None): tags = {} if tags_add: tags["add"] = self._listify(tags_add) if tags_remove: tags["remove"] = self._listify(tags_remove) d = { "ids": self._listify(idlist), "tags": tags, } return self._proxy.Bug.update_tags(d)
[ "def", "update_tags", "(", "self", ",", "idlist", ",", "tags_add", "=", "None", ",", "tags_remove", "=", "None", ")", ":", "tags", "=", "{", "}", "if", "tags_add", ":", "tags", "[", "\"add\"", "]", "=", "self", ".", "_listify", "(", "tags_add", ")", ...
Updates the 'tags' field for a bug.
[ "Updates", "the", "tags", "field", "for", "a", "bug", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1328-L1343
26,570
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._attachment_uri
def _attachment_uri(self, attachid): """ Returns the URI for the given attachment ID. """ att_uri = self.url.replace('xmlrpc.cgi', 'attachment.cgi') att_uri = att_uri + '?id=%s' % attachid return att_uri
python
def _attachment_uri(self, attachid): att_uri = self.url.replace('xmlrpc.cgi', 'attachment.cgi') att_uri = att_uri + '?id=%s' % attachid return att_uri
[ "def", "_attachment_uri", "(", "self", ",", "attachid", ")", ":", "att_uri", "=", "self", ".", "url", ".", "replace", "(", "'xmlrpc.cgi'", ",", "'attachment.cgi'", ")", "att_uri", "=", "att_uri", "+", "'?id=%s'", "%", "attachid", "return", "att_uri" ]
Returns the URI for the given attachment ID.
[ "Returns", "the", "URI", "for", "the", "given", "attachment", "ID", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1501-L1507
26,571
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.attachfile
def attachfile(self, idlist, attachfile, description, **kwargs): """ Attach a file to the given bug IDs. Returns the ID of the attachment or raises XMLRPC Fault if something goes wrong. attachfile may be a filename (which will be opened) or a file-like object, which must provide a 'read' method. If it's not one of these, this method will raise a TypeError. description is the short description of this attachment. Optional keyword args are as follows: file_name: this will be used as the filename for the attachment. REQUIRED if attachfile is a file-like object with no 'name' attribute, otherwise the filename or .name attribute will be used. comment: An optional comment about this attachment. is_private: Set to True if the attachment should be marked private. is_patch: Set to True if the attachment is a patch. content_type: The mime-type of the attached file. Defaults to application/octet-stream if not set. NOTE that text files will *not* be viewable in bugzilla unless you remember to set this to text/plain. So remember that! Returns the list of attachment ids that were added. If only one attachment was added, we return the single int ID for back compat """ if isinstance(attachfile, str): f = open(attachfile, "rb") elif hasattr(attachfile, 'read'): f = attachfile else: raise TypeError("attachfile must be filename or file-like object") # Back compat if "contenttype" in kwargs: kwargs["content_type"] = kwargs.pop("contenttype") if "ispatch" in kwargs: kwargs["is_patch"] = kwargs.pop("ispatch") if "isprivate" in kwargs: kwargs["is_private"] = kwargs.pop("isprivate") if "filename" in kwargs: kwargs["file_name"] = kwargs.pop("filename") kwargs['summary'] = description data = f.read() if not isinstance(data, bytes): data = data.encode(locale.getpreferredencoding()) kwargs['data'] = Binary(data) kwargs['ids'] = self._listify(idlist) if 'file_name' not in kwargs and hasattr(f, "name"): kwargs['file_name'] = os.path.basename(f.name) if 'content_type' not in kwargs: ctype = None if kwargs['file_name']: ctype = mimetypes.guess_type( kwargs['file_name'], strict=False)[0] kwargs['content_type'] = ctype or 'application/octet-stream' ret = self._proxy.Bug.add_attachment(kwargs) if "attachments" in ret: # Up to BZ 4.2 ret = [int(k) for k in ret["attachments"].keys()] elif "ids" in ret: # BZ 4.4+ ret = ret["ids"] if isinstance(ret, list) and len(ret) == 1: ret = ret[0] return ret
python
def attachfile(self, idlist, attachfile, description, **kwargs): if isinstance(attachfile, str): f = open(attachfile, "rb") elif hasattr(attachfile, 'read'): f = attachfile else: raise TypeError("attachfile must be filename or file-like object") # Back compat if "contenttype" in kwargs: kwargs["content_type"] = kwargs.pop("contenttype") if "ispatch" in kwargs: kwargs["is_patch"] = kwargs.pop("ispatch") if "isprivate" in kwargs: kwargs["is_private"] = kwargs.pop("isprivate") if "filename" in kwargs: kwargs["file_name"] = kwargs.pop("filename") kwargs['summary'] = description data = f.read() if not isinstance(data, bytes): data = data.encode(locale.getpreferredencoding()) kwargs['data'] = Binary(data) kwargs['ids'] = self._listify(idlist) if 'file_name' not in kwargs and hasattr(f, "name"): kwargs['file_name'] = os.path.basename(f.name) if 'content_type' not in kwargs: ctype = None if kwargs['file_name']: ctype = mimetypes.guess_type( kwargs['file_name'], strict=False)[0] kwargs['content_type'] = ctype or 'application/octet-stream' ret = self._proxy.Bug.add_attachment(kwargs) if "attachments" in ret: # Up to BZ 4.2 ret = [int(k) for k in ret["attachments"].keys()] elif "ids" in ret: # BZ 4.4+ ret = ret["ids"] if isinstance(ret, list) and len(ret) == 1: ret = ret[0] return ret
[ "def", "attachfile", "(", "self", ",", "idlist", ",", "attachfile", ",", "description", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "attachfile", ",", "str", ")", ":", "f", "=", "open", "(", "attachfile", ",", "\"rb\"", ")", "elif", "...
Attach a file to the given bug IDs. Returns the ID of the attachment or raises XMLRPC Fault if something goes wrong. attachfile may be a filename (which will be opened) or a file-like object, which must provide a 'read' method. If it's not one of these, this method will raise a TypeError. description is the short description of this attachment. Optional keyword args are as follows: file_name: this will be used as the filename for the attachment. REQUIRED if attachfile is a file-like object with no 'name' attribute, otherwise the filename or .name attribute will be used. comment: An optional comment about this attachment. is_private: Set to True if the attachment should be marked private. is_patch: Set to True if the attachment is a patch. content_type: The mime-type of the attached file. Defaults to application/octet-stream if not set. NOTE that text files will *not* be viewable in bugzilla unless you remember to set this to text/plain. So remember that! Returns the list of attachment ids that were added. If only one attachment was added, we return the single int ID for back compat
[ "Attach", "a", "file", "to", "the", "given", "bug", "IDs", ".", "Returns", "the", "ID", "of", "the", "attachment", "or", "raises", "XMLRPC", "Fault", "if", "something", "goes", "wrong", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1509-L1581
26,572
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.openattachment
def openattachment(self, attachid): """ Get the contents of the attachment with the given attachment ID. Returns a file-like object. """ attachments = self.get_attachments(None, attachid) data = attachments["attachments"][str(attachid)] xmlrpcbinary = data["data"] ret = BytesIO() ret.write(xmlrpcbinary.data) ret.name = data["file_name"] ret.seek(0) return ret
python
def openattachment(self, attachid): attachments = self.get_attachments(None, attachid) data = attachments["attachments"][str(attachid)] xmlrpcbinary = data["data"] ret = BytesIO() ret.write(xmlrpcbinary.data) ret.name = data["file_name"] ret.seek(0) return ret
[ "def", "openattachment", "(", "self", ",", "attachid", ")", ":", "attachments", "=", "self", ".", "get_attachments", "(", "None", ",", "attachid", ")", "data", "=", "attachments", "[", "\"attachments\"", "]", "[", "str", "(", "attachid", ")", "]", "xmlrpcb...
Get the contents of the attachment with the given attachment ID. Returns a file-like object.
[ "Get", "the", "contents", "of", "the", "attachment", "with", "the", "given", "attachment", "ID", ".", "Returns", "a", "file", "-", "like", "object", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1584-L1597
26,573
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.get_attachments
def get_attachments(self, ids, attachment_ids, include_fields=None, exclude_fields=None): """ Wrapper for Bug.attachments. One of ids or attachment_ids is required :param ids: Get attachments for this bug ID :param attachment_ids: Specific attachment ID to get https://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#get-attachment """ params = { "ids": self._listify(ids) or [], "attachment_ids": self._listify(attachment_ids) or [], } if include_fields: params["include_fields"] = self._listify(include_fields) if exclude_fields: params["exclude_fields"] = self._listify(exclude_fields) return self._proxy.Bug.attachments(params)
python
def get_attachments(self, ids, attachment_ids, include_fields=None, exclude_fields=None): params = { "ids": self._listify(ids) or [], "attachment_ids": self._listify(attachment_ids) or [], } if include_fields: params["include_fields"] = self._listify(include_fields) if exclude_fields: params["exclude_fields"] = self._listify(exclude_fields) return self._proxy.Bug.attachments(params)
[ "def", "get_attachments", "(", "self", ",", "ids", ",", "attachment_ids", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ")", ":", "params", "=", "{", "\"ids\"", ":", "self", ".", "_listify", "(", "ids", ")", "or", "[", "]", ",...
Wrapper for Bug.attachments. One of ids or attachment_ids is required :param ids: Get attachments for this bug ID :param attachment_ids: Specific attachment ID to get https://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#get-attachment
[ "Wrapper", "for", "Bug", ".", "attachments", ".", "One", "of", "ids", "or", "attachment_ids", "is", "required" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1616-L1635
26,574
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.createbug
def createbug(self, *args, **kwargs): """ Create a bug with the given info. Returns a new Bug object. Check bugzilla API documentation for valid values, at least product, component, summary, version, and description need to be passed. """ data = self._validate_createbug(*args, **kwargs) rawbug = self._proxy.Bug.create(data) return Bug(self, bug_id=rawbug["id"], autorefresh=self.bug_autorefresh)
python
def createbug(self, *args, **kwargs): data = self._validate_createbug(*args, **kwargs) rawbug = self._proxy.Bug.create(data) return Bug(self, bug_id=rawbug["id"], autorefresh=self.bug_autorefresh)
[ "def", "createbug", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "_validate_createbug", "(", "*", "args", ",", "*", "*", "kwargs", ")", "rawbug", "=", "self", ".", "_proxy", ".", "Bug", ".", "create", ...
Create a bug with the given info. Returns a new Bug object. Check bugzilla API documentation for valid values, at least product, component, summary, version, and description need to be passed.
[ "Create", "a", "bug", "with", "the", "given", "info", ".", "Returns", "a", "new", "Bug", "object", ".", "Check", "bugzilla", "API", "documentation", "for", "valid", "values", "at", "least", "product", "component", "summary", "version", "and", "description", ...
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1739-L1749
26,575
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._getusers
def _getusers(self, ids=None, names=None, match=None): """ Return a list of users that match criteria. :kwarg ids: list of user ids to return data on :kwarg names: list of user names to return data on :kwarg match: list of patterns. Returns users whose real name or login name match the pattern. :raises XMLRPC Fault: Code 51: if a Bad Login Name was sent to the names array. Code 304: if the user was not authorized to see user they requested. Code 505: user is logged out and can't use the match or ids parameter. Available in Bugzilla-3.4+ """ params = {} if ids: params['ids'] = self._listify(ids) if names: params['names'] = self._listify(names) if match: params['match'] = self._listify(match) if not params: raise BugzillaError('_get() needs one of ids, ' ' names, or match kwarg.') return self._proxy.User.get(params)
python
def _getusers(self, ids=None, names=None, match=None): params = {} if ids: params['ids'] = self._listify(ids) if names: params['names'] = self._listify(names) if match: params['match'] = self._listify(match) if not params: raise BugzillaError('_get() needs one of ids, ' ' names, or match kwarg.') return self._proxy.User.get(params)
[ "def", "_getusers", "(", "self", ",", "ids", "=", "None", ",", "names", "=", "None", ",", "match", "=", "None", ")", ":", "params", "=", "{", "}", "if", "ids", ":", "params", "[", "'ids'", "]", "=", "self", ".", "_listify", "(", "ids", ")", "if...
Return a list of users that match criteria. :kwarg ids: list of user ids to return data on :kwarg names: list of user names to return data on :kwarg match: list of patterns. Returns users whose real name or login name match the pattern. :raises XMLRPC Fault: Code 51: if a Bad Login Name was sent to the names array. Code 304: if the user was not authorized to see user they requested. Code 505: user is logged out and can't use the match or ids parameter. Available in Bugzilla-3.4+
[ "Return", "a", "list", "of", "users", "that", "match", "criteria", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1756-L1784
26,576
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getusers
def getusers(self, userlist): """ Return a list of Users from . :userlist: List of usernames to lookup :returns: List of User records """ userobjs = [User(self, **rawuser) for rawuser in self._getusers(names=userlist).get('users', [])] # Return users in same order they were passed in ret = [] for u in userlist: for uobj in userobjs[:]: if uobj.email == u: userobjs.remove(uobj) ret.append(uobj) break ret += userobjs return ret
python
def getusers(self, userlist): userobjs = [User(self, **rawuser) for rawuser in self._getusers(names=userlist).get('users', [])] # Return users in same order they were passed in ret = [] for u in userlist: for uobj in userobjs[:]: if uobj.email == u: userobjs.remove(uobj) ret.append(uobj) break ret += userobjs return ret
[ "def", "getusers", "(", "self", ",", "userlist", ")", ":", "userobjs", "=", "[", "User", "(", "self", ",", "*", "*", "rawuser", ")", "for", "rawuser", "in", "self", ".", "_getusers", "(", "names", "=", "userlist", ")", ".", "get", "(", "'users'", "...
Return a list of Users from . :userlist: List of usernames to lookup :returns: List of User records
[ "Return", "a", "list", "of", "Users", "from", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1797-L1816
26,577
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.searchusers
def searchusers(self, pattern): """ Return a bugzilla User for the given list of patterns :arg pattern: List of patterns to match against. :returns: List of User records """ return [User(self, **rawuser) for rawuser in self._getusers(match=pattern).get('users', [])]
python
def searchusers(self, pattern): return [User(self, **rawuser) for rawuser in self._getusers(match=pattern).get('users', [])]
[ "def", "searchusers", "(", "self", ",", "pattern", ")", ":", "return", "[", "User", "(", "self", ",", "*", "*", "rawuser", ")", "for", "rawuser", "in", "self", ".", "_getusers", "(", "match", "=", "pattern", ")", ".", "get", "(", "'users'", ",", "[...
Return a bugzilla User for the given list of patterns :arg pattern: List of patterns to match against. :returns: List of User records
[ "Return", "a", "bugzilla", "User", "for", "the", "given", "list", "of", "patterns" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1819-L1827
26,578
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.createuser
def createuser(self, email, name='', password=''): """ Return a bugzilla User for the given username :arg email: The email address to use in bugzilla :kwarg name: Real name to associate with the account :kwarg password: Password to set for the bugzilla account :raises XMLRPC Fault: Code 501 if the username already exists Code 500 if the email address isn't valid Code 502 if the password is too short Code 503 if the password is too long :return: User record for the username """ self._proxy.User.create(email, name, password) return self.getuser(email)
python
def createuser(self, email, name='', password=''): self._proxy.User.create(email, name, password) return self.getuser(email)
[ "def", "createuser", "(", "self", ",", "email", ",", "name", "=", "''", ",", "password", "=", "''", ")", ":", "self", ".", "_proxy", ".", "User", ".", "create", "(", "email", ",", "name", ",", "password", ")", "return", "self", ".", "getuser", "(",...
Return a bugzilla User for the given username :arg email: The email address to use in bugzilla :kwarg name: Real name to associate with the account :kwarg password: Password to set for the bugzilla account :raises XMLRPC Fault: Code 501 if the username already exists Code 500 if the email address isn't valid Code 502 if the password is too short Code 503 if the password is too long :return: User record for the username
[ "Return", "a", "bugzilla", "User", "for", "the", "given", "username" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1829-L1843
26,579
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.refresh
def refresh(self, include_fields=None, exclude_fields=None, extra_fields=None): """ Refresh the bug with the latest data from bugzilla """ # pylint: disable=protected-access r = self.bugzilla._getbug(self.bug_id, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=self._bug_fields + (extra_fields or [])) # pylint: enable=protected-access self._update_dict(r)
python
def refresh(self, include_fields=None, exclude_fields=None, extra_fields=None): # pylint: disable=protected-access r = self.bugzilla._getbug(self.bug_id, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=self._bug_fields + (extra_fields or [])) # pylint: enable=protected-access self._update_dict(r)
[ "def", "refresh", "(", "self", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "extra_fields", "=", "None", ")", ":", "# pylint: disable=protected-access", "r", "=", "self", ".", "bugzilla", ".", "_getbug", "(", "self", ".", "bug...
Refresh the bug with the latest data from bugzilla
[ "Refresh", "the", "bug", "with", "the", "latest", "data", "from", "bugzilla" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L117-L127
26,580
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug._update_dict
def _update_dict(self, newdict): """ Update internal dictionary, in a way that ensures no duplicate entries are stored WRT field aliases """ if self.bugzilla: self.bugzilla.post_translation({}, newdict) # pylint: disable=protected-access aliases = self.bugzilla._get_bug_aliases() # pylint: enable=protected-access for newname, oldname in aliases: if oldname not in newdict: continue if newname not in newdict: newdict[newname] = newdict[oldname] elif newdict[newname] != newdict[oldname]: log.debug("Update dict contained differing alias values " "d[%s]=%s and d[%s]=%s , dropping the value " "d[%s]", newname, newdict[newname], oldname, newdict[oldname], oldname) del(newdict[oldname]) for key in newdict.keys(): if key not in self._bug_fields: self._bug_fields.append(key) self.__dict__.update(newdict) if 'id' not in self.__dict__ and 'bug_id' not in self.__dict__: raise TypeError("Bug object needs a bug_id")
python
def _update_dict(self, newdict): if self.bugzilla: self.bugzilla.post_translation({}, newdict) # pylint: disable=protected-access aliases = self.bugzilla._get_bug_aliases() # pylint: enable=protected-access for newname, oldname in aliases: if oldname not in newdict: continue if newname not in newdict: newdict[newname] = newdict[oldname] elif newdict[newname] != newdict[oldname]: log.debug("Update dict contained differing alias values " "d[%s]=%s and d[%s]=%s , dropping the value " "d[%s]", newname, newdict[newname], oldname, newdict[oldname], oldname) del(newdict[oldname]) for key in newdict.keys(): if key not in self._bug_fields: self._bug_fields.append(key) self.__dict__.update(newdict) if 'id' not in self.__dict__ and 'bug_id' not in self.__dict__: raise TypeError("Bug object needs a bug_id")
[ "def", "_update_dict", "(", "self", ",", "newdict", ")", ":", "if", "self", ".", "bugzilla", ":", "self", ".", "bugzilla", ".", "post_translation", "(", "{", "}", ",", "newdict", ")", "# pylint: disable=protected-access", "aliases", "=", "self", ".", "bugzil...
Update internal dictionary, in a way that ensures no duplicate entries are stored WRT field aliases
[ "Update", "internal", "dictionary", "in", "a", "way", "that", "ensures", "no", "duplicate", "entries", "are", "stored", "WRT", "field", "aliases" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L130-L161
26,581
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.deletecc
def deletecc(self, cclist, comment=None): """ Removes the given email addresses from the CC list for this bug. """ vals = self.bugzilla.build_update(comment=comment, cc_remove=cclist) log.debug("deletecc: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals)
python
def deletecc(self, cclist, comment=None): vals = self.bugzilla.build_update(comment=comment, cc_remove=cclist) log.debug("deletecc: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals)
[ "def", "deletecc", "(", "self", ",", "cclist", ",", "comment", "=", "None", ")", ":", "vals", "=", "self", ".", "bugzilla", ".", "build_update", "(", "comment", "=", "comment", ",", "cc_remove", "=", "cclist", ")", "log", ".", "debug", "(", "\"deletecc...
Removes the given email addresses from the CC list for this bug.
[ "Removes", "the", "given", "email", "addresses", "from", "the", "CC", "list", "for", "this", "bug", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L267-L275
26,582
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.addcomment
def addcomment(self, comment, private=False): """ Add the given comment to this bug. Set private to True to mark this comment as private. """ # Note: fedora bodhi uses this function vals = self.bugzilla.build_update(comment=comment, comment_private=private) log.debug("addcomment: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals)
python
def addcomment(self, comment, private=False): # Note: fedora bodhi uses this function vals = self.bugzilla.build_update(comment=comment, comment_private=private) log.debug("addcomment: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals)
[ "def", "addcomment", "(", "self", ",", "comment", ",", "private", "=", "False", ")", ":", "# Note: fedora bodhi uses this function", "vals", "=", "self", ".", "bugzilla", ".", "build_update", "(", "comment", "=", "comment", ",", "comment_private", "=", "private"...
Add the given comment to this bug. Set private to True to mark this comment as private.
[ "Add", "the", "given", "comment", "to", "this", "bug", ".", "Set", "private", "to", "True", "to", "mark", "this", "comment", "as", "private", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L282-L292
26,583
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.getcomments
def getcomments(self): """ Returns an array of comment dictionaries for this bug """ comment_list = self.bugzilla.get_comments([self.bug_id]) return comment_list['bugs'][str(self.bug_id)]['comments']
python
def getcomments(self): comment_list = self.bugzilla.get_comments([self.bug_id]) return comment_list['bugs'][str(self.bug_id)]['comments']
[ "def", "getcomments", "(", "self", ")", ":", "comment_list", "=", "self", ".", "bugzilla", ".", "get_comments", "(", "[", "self", ".", "bug_id", "]", ")", "return", "comment_list", "[", "'bugs'", "]", "[", "str", "(", "self", ".", "bug_id", ")", "]", ...
Returns an array of comment dictionaries for this bug
[ "Returns", "an", "array", "of", "comment", "dictionaries", "for", "this", "bug" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L294-L299
26,584
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.get_flag_status
def get_flag_status(self, name): """ Return a flag 'status' field This method works only for simple flags that have only a 'status' field with no "requestee" info, and no multiple values. For more complex flags, use get_flags() to get extended flag value information. """ f = self.get_flags(name) if not f: return None # This method works only for simple flags that have only one # value set. assert len(f) <= 1 return f[0]['status']
python
def get_flag_status(self, name): f = self.get_flags(name) if not f: return None # This method works only for simple flags that have only one # value set. assert len(f) <= 1 return f[0]['status']
[ "def", "get_flag_status", "(", "self", ",", "name", ")", ":", "f", "=", "self", ".", "get_flags", "(", "name", ")", "if", "not", "f", ":", "return", "None", "# This method works only for simple flags that have only one", "# value set.", "assert", "len", "(", "f"...
Return a flag 'status' field This method works only for simple flags that have only a 'status' field with no "requestee" info, and no multiple values. For more complex flags, use get_flags() to get extended flag value information.
[ "Return", "a", "flag", "status", "field" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L328-L344
26,585
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.get_attachments
def get_attachments(self, include_fields=None, exclude_fields=None): """ Helper call to Bugzilla.get_attachments. If you want to fetch specific attachment IDs, use that function instead """ if "attachments" in self.__dict__: return self.attachments data = self.bugzilla.get_attachments([self.bug_id], None, include_fields, exclude_fields) return data["bugs"][str(self.bug_id)]
python
def get_attachments(self, include_fields=None, exclude_fields=None): if "attachments" in self.__dict__: return self.attachments data = self.bugzilla.get_attachments([self.bug_id], None, include_fields, exclude_fields) return data["bugs"][str(self.bug_id)]
[ "def", "get_attachments", "(", "self", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ")", ":", "if", "\"attachments\"", "in", "self", ".", "__dict__", ":", "return", "self", ".", "attachments", "data", "=", "self", ".", "bugzilla", ...
Helper call to Bugzilla.get_attachments. If you want to fetch specific attachment IDs, use that function instead
[ "Helper", "call", "to", "Bugzilla", ".", "get_attachments", ".", "If", "you", "want", "to", "fetch", "specific", "attachment", "IDs", "use", "that", "function", "instead" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L366-L376
26,586
python-bugzilla/python-bugzilla
bugzilla/bug.py
User.refresh
def refresh(self): """ Update User object with latest info from bugzilla """ newuser = self.bugzilla.getuser(self.email) self.__dict__.update(newuser.__dict__)
python
def refresh(self): newuser = self.bugzilla.getuser(self.email) self.__dict__.update(newuser.__dict__)
[ "def", "refresh", "(", "self", ")", ":", "newuser", "=", "self", ".", "bugzilla", ".", "getuser", "(", "self", ".", "email", ")", "self", ".", "__dict__", ".", "update", "(", "newuser", ".", "__dict__", ")" ]
Update User object with latest info from bugzilla
[ "Update", "User", "object", "with", "latest", "info", "from", "bugzilla" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L441-L446
26,587
python-bugzilla/python-bugzilla
bugzilla/rhbugzilla.py
RHBugzilla.pre_translation
def pre_translation(self, query): """ Translates the query for possible aliases """ old = query.copy() if 'bug_id' in query: if not isinstance(query['bug_id'], list): query['id'] = query['bug_id'].split(',') else: query['id'] = query['bug_id'] del query['bug_id'] if 'component' in query: if not isinstance(query['component'], list): query['component'] = query['component'].split(',') if 'include_fields' not in query and 'column_list' not in query: return if 'include_fields' not in query: query['include_fields'] = [] if 'column_list' in query: query['include_fields'] = query['column_list'] del query['column_list'] # We need to do this for users here for users that # don't call build_query query.update(self._process_include_fields(query["include_fields"], None, None)) if old != query: log.debug("RHBugzilla pretranslated query to: %s", query)
python
def pre_translation(self, query): old = query.copy() if 'bug_id' in query: if not isinstance(query['bug_id'], list): query['id'] = query['bug_id'].split(',') else: query['id'] = query['bug_id'] del query['bug_id'] if 'component' in query: if not isinstance(query['component'], list): query['component'] = query['component'].split(',') if 'include_fields' not in query and 'column_list' not in query: return if 'include_fields' not in query: query['include_fields'] = [] if 'column_list' in query: query['include_fields'] = query['column_list'] del query['column_list'] # We need to do this for users here for users that # don't call build_query query.update(self._process_include_fields(query["include_fields"], None, None)) if old != query: log.debug("RHBugzilla pretranslated query to: %s", query)
[ "def", "pre_translation", "(", "self", ",", "query", ")", ":", "old", "=", "query", ".", "copy", "(", ")", "if", "'bug_id'", "in", "query", ":", "if", "not", "isinstance", "(", "query", "[", "'bug_id'", "]", ",", "list", ")", ":", "query", "[", "'i...
Translates the query for possible aliases
[ "Translates", "the", "query", "for", "possible", "aliases" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/rhbugzilla.py#L252-L284
26,588
python-bugzilla/python-bugzilla
bugzilla/rhbugzilla.py
RHBugzilla.post_translation
def post_translation(self, query, bug): """ Convert the results of getbug back to the ancient RHBZ value formats """ ignore = query # RHBZ _still_ returns component and version as lists, which # deviates from upstream. Copy the list values to components # and versions respectively. if 'component' in bug and "components" not in bug: val = bug['component'] bug['components'] = isinstance(val, list) and val or [val] bug['component'] = bug['components'][0] if 'version' in bug and "versions" not in bug: val = bug['version'] bug['versions'] = isinstance(val, list) and val or [val] bug['version'] = bug['versions'][0] # sub_components isn't too friendly of a format, add a simpler # sub_component value if 'sub_components' in bug and 'sub_component' not in bug: val = bug['sub_components'] bug['sub_component'] = "" if isinstance(val, dict): values = [] for vallist in val.values(): values += vallist bug['sub_component'] = " ".join(values)
python
def post_translation(self, query, bug): ignore = query # RHBZ _still_ returns component and version as lists, which # deviates from upstream. Copy the list values to components # and versions respectively. if 'component' in bug and "components" not in bug: val = bug['component'] bug['components'] = isinstance(val, list) and val or [val] bug['component'] = bug['components'][0] if 'version' in bug and "versions" not in bug: val = bug['version'] bug['versions'] = isinstance(val, list) and val or [val] bug['version'] = bug['versions'][0] # sub_components isn't too friendly of a format, add a simpler # sub_component value if 'sub_components' in bug and 'sub_component' not in bug: val = bug['sub_components'] bug['sub_component'] = "" if isinstance(val, dict): values = [] for vallist in val.values(): values += vallist bug['sub_component'] = " ".join(values)
[ "def", "post_translation", "(", "self", ",", "query", ",", "bug", ")", ":", "ignore", "=", "query", "# RHBZ _still_ returns component and version as lists, which", "# deviates from upstream. Copy the list values to components", "# and versions respectively.", "if", "'component'", ...
Convert the results of getbug back to the ancient RHBZ value formats
[ "Convert", "the", "results", "of", "getbug", "back", "to", "the", "ancient", "RHBZ", "value", "formats" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/rhbugzilla.py#L286-L315
26,589
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete
def delete(self, mail): """ Delete a mail from the filesystem. """ self.stats['mail_deleted'] += 1 if self.conf.dry_run: logger.info("Skip deletion of {!r}.".format(mail)) return logger.debug("Deleting {!r}...".format(mail)) # XXX Investigate the use of maildir's .remove instead. See: https: # //github.com/python/cpython/blob/origin/2.7/Lib/mailbox.py#L329-L331 os.unlink(mail.path) logger.info("{} deleted.".format(mail.path))
python
def delete(self, mail): self.stats['mail_deleted'] += 1 if self.conf.dry_run: logger.info("Skip deletion of {!r}.".format(mail)) return logger.debug("Deleting {!r}...".format(mail)) # XXX Investigate the use of maildir's .remove instead. See: https: # //github.com/python/cpython/blob/origin/2.7/Lib/mailbox.py#L329-L331 os.unlink(mail.path) logger.info("{} deleted.".format(mail.path))
[ "def", "delete", "(", "self", ",", "mail", ")", ":", "self", ".", "stats", "[", "'mail_deleted'", "]", "+=", "1", "if", "self", ".", "conf", ".", "dry_run", ":", "logger", ".", "info", "(", "\"Skip deletion of {!r}.\"", ".", "format", "(", "mail", ")",...
Delete a mail from the filesystem.
[ "Delete", "a", "mail", "from", "the", "filesystem", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L109-L120
26,590
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.check_differences
def check_differences(self): """ In-depth check of mail differences. Compare all mails of the duplicate set with each other, both in size and content. Raise an error if we're not within the limits imposed by the threshold setting. """ logger.info("Check that mail differences are within the limits.") if self.conf.size_threshold < 0: logger.info("Skip checking for size differences.") if self.conf.content_threshold < 0: logger.info("Skip checking for content differences.") if self.conf.size_threshold < 0 and self.conf.content_threshold < 0: return # Compute differences of mail against one another. for mail_a, mail_b in combinations(self.pool, 2): # Compare mails on size. if self.conf.size_threshold > -1: size_difference = abs(mail_a.size - mail_b.size) logger.debug("{} and {} differs by {} bytes in size.".format( mail_a, mail_b, size_difference)) if size_difference > self.conf.size_threshold: raise SizeDiffAboveThreshold # Compare mails on content. if self.conf.content_threshold > -1: content_difference = self.diff(mail_a, mail_b) logger.debug( "{} and {} differs by {} bytes in content.".format( mail_a, mail_b, content_difference)) if content_difference > self.conf.content_threshold: if self.conf.show_diff: logger.info(self.pretty_diff(mail_a, mail_b)) raise ContentDiffAboveThreshold
python
def check_differences(self): logger.info("Check that mail differences are within the limits.") if self.conf.size_threshold < 0: logger.info("Skip checking for size differences.") if self.conf.content_threshold < 0: logger.info("Skip checking for content differences.") if self.conf.size_threshold < 0 and self.conf.content_threshold < 0: return # Compute differences of mail against one another. for mail_a, mail_b in combinations(self.pool, 2): # Compare mails on size. if self.conf.size_threshold > -1: size_difference = abs(mail_a.size - mail_b.size) logger.debug("{} and {} differs by {} bytes in size.".format( mail_a, mail_b, size_difference)) if size_difference > self.conf.size_threshold: raise SizeDiffAboveThreshold # Compare mails on content. if self.conf.content_threshold > -1: content_difference = self.diff(mail_a, mail_b) logger.debug( "{} and {} differs by {} bytes in content.".format( mail_a, mail_b, content_difference)) if content_difference > self.conf.content_threshold: if self.conf.show_diff: logger.info(self.pretty_diff(mail_a, mail_b)) raise ContentDiffAboveThreshold
[ "def", "check_differences", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Check that mail differences are within the limits.\"", ")", "if", "self", ".", "conf", ".", "size_threshold", "<", "0", ":", "logger", ".", "info", "(", "\"Skip checking for size diffe...
In-depth check of mail differences. Compare all mails of the duplicate set with each other, both in size and content. Raise an error if we're not within the limits imposed by the threshold setting.
[ "In", "-", "depth", "check", "of", "mail", "differences", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L122-L157
26,591
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.diff
def diff(self, mail_a, mail_b): """ Return difference in bytes between two mails' normalized body. TODO: rewrite the diff algorithm to not rely on naive unified diff result parsing. """ return len(''.join(unified_diff( mail_a.body_lines, mail_b.body_lines, # Ignore difference in filename lenghts and timestamps. fromfile='a', tofile='b', fromfiledate='', tofiledate='', n=0, lineterm='\n')))
python
def diff(self, mail_a, mail_b): return len(''.join(unified_diff( mail_a.body_lines, mail_b.body_lines, # Ignore difference in filename lenghts and timestamps. fromfile='a', tofile='b', fromfiledate='', tofiledate='', n=0, lineterm='\n')))
[ "def", "diff", "(", "self", ",", "mail_a", ",", "mail_b", ")", ":", "return", "len", "(", "''", ".", "join", "(", "unified_diff", "(", "mail_a", ".", "body_lines", ",", "mail_b", ".", "body_lines", ",", "# Ignore difference in filename lenghts and timestamps.", ...
Return difference in bytes between two mails' normalized body. TODO: rewrite the diff algorithm to not rely on naive unified diff result parsing.
[ "Return", "difference", "in", "bytes", "between", "two", "mails", "normalized", "body", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L159-L170
26,592
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.pretty_diff
def pretty_diff(self, mail_a, mail_b): """ Returns a verbose unified diff between two mails' normalized body. """ return ''.join(unified_diff( mail_a.body_lines, mail_b.body_lines, fromfile='Normalized body of {}'.format(mail_a.path), tofile='Normalized body of {}'.format(mail_b.path), fromfiledate='{:0.2f}'.format(mail_a.timestamp), tofiledate='{:0.2f}'.format(mail_b.timestamp), n=0, lineterm='\n'))
python
def pretty_diff(self, mail_a, mail_b): return ''.join(unified_diff( mail_a.body_lines, mail_b.body_lines, fromfile='Normalized body of {}'.format(mail_a.path), tofile='Normalized body of {}'.format(mail_b.path), fromfiledate='{:0.2f}'.format(mail_a.timestamp), tofiledate='{:0.2f}'.format(mail_b.timestamp), n=0, lineterm='\n'))
[ "def", "pretty_diff", "(", "self", ",", "mail_a", ",", "mail_b", ")", ":", "return", "''", ".", "join", "(", "unified_diff", "(", "mail_a", ".", "body_lines", ",", "mail_b", ".", "body_lines", ",", "fromfile", "=", "'Normalized body of {}'", ".", "format", ...
Returns a verbose unified diff between two mails' normalized body.
[ "Returns", "a", "verbose", "unified", "diff", "between", "two", "mails", "normalized", "body", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L172-L181
26,593
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.apply_strategy
def apply_strategy(self): """ Apply deduplication with the configured strategy. Transform strategy keyword into its method ID, and call it. """ method_id = self.conf.strategy.replace('-', '_') if not hasattr(DuplicateSet, method_id): raise NotImplementedError( "DuplicateSet.{}() method.".format(method_id)) return getattr(self, method_id)()
python
def apply_strategy(self): method_id = self.conf.strategy.replace('-', '_') if not hasattr(DuplicateSet, method_id): raise NotImplementedError( "DuplicateSet.{}() method.".format(method_id)) return getattr(self, method_id)()
[ "def", "apply_strategy", "(", "self", ")", ":", "method_id", "=", "self", ".", "conf", ".", "strategy", ".", "replace", "(", "'-'", ",", "'_'", ")", "if", "not", "hasattr", "(", "DuplicateSet", ",", "method_id", ")", ":", "raise", "NotImplementedError", ...
Apply deduplication with the configured strategy. Transform strategy keyword into its method ID, and call it.
[ "Apply", "deduplication", "with", "the", "configured", "strategy", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L183-L192
26,594
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.dedupe
def dedupe(self): """ Performs the deduplication and its preliminary checks. """ if len(self.pool) == 1: logger.debug("Ignore set: only one message found.") self.stats['mail_unique'] += 1 self.stats['set_ignored'] += 1 return try: # Fine-grained checks on mail differences. self.check_differences() # Call the deduplication strategy. self.apply_strategy() except UnicodeDecodeError as expt: self.stats['set_rejected_encoding'] += 1 logger.warning( "Reject set: unparseable mails due to bad encoding.") logger.debug(str(expt)) except SizeDiffAboveThreshold: self.stats['set_rejected_size'] += 1 logger.warning("Reject set: mails are too dissimilar in size.") except ContentDiffAboveThreshold: self.stats['set_rejected_content'] += 1 logger.warning("Reject set: mails are too dissimilar in content.") else: # Count duplicate sets without deletion as skipped. if not self.stats['mail_deleted']: logger.info("Skip set: no deletion happened.") self.stats['set_skipped'] += 1 else: self.stats['set_deduplicated'] += 1
python
def dedupe(self): if len(self.pool) == 1: logger.debug("Ignore set: only one message found.") self.stats['mail_unique'] += 1 self.stats['set_ignored'] += 1 return try: # Fine-grained checks on mail differences. self.check_differences() # Call the deduplication strategy. self.apply_strategy() except UnicodeDecodeError as expt: self.stats['set_rejected_encoding'] += 1 logger.warning( "Reject set: unparseable mails due to bad encoding.") logger.debug(str(expt)) except SizeDiffAboveThreshold: self.stats['set_rejected_size'] += 1 logger.warning("Reject set: mails are too dissimilar in size.") except ContentDiffAboveThreshold: self.stats['set_rejected_content'] += 1 logger.warning("Reject set: mails are too dissimilar in content.") else: # Count duplicate sets without deletion as skipped. if not self.stats['mail_deleted']: logger.info("Skip set: no deletion happened.") self.stats['set_skipped'] += 1 else: self.stats['set_deduplicated'] += 1
[ "def", "dedupe", "(", "self", ")", ":", "if", "len", "(", "self", ".", "pool", ")", "==", "1", ":", "logger", ".", "debug", "(", "\"Ignore set: only one message found.\"", ")", "self", ".", "stats", "[", "'mail_unique'", "]", "+=", "1", "self", ".", "s...
Performs the deduplication and its preliminary checks.
[ "Performs", "the", "deduplication", "and", "its", "preliminary", "checks", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L194-L224
26,595
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_older
def delete_older(self): """ Delete all older duplicates. Only keeps the subset sharing the most recent timestamp. """ logger.info( "Deleting all mails strictly older than the {} timestamp..." "".format(self.newest_timestamp)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.timestamp < self.newest_timestamp] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same timestamp." "".format(self.size)) logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_older(self): logger.info( "Deleting all mails strictly older than the {} timestamp..." "".format(self.newest_timestamp)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.timestamp < self.newest_timestamp] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same timestamp." "".format(self.size)) logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_older", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails strictly older than the {} timestamp...\"", "\"\"", ".", "format", "(", "self", ".", "newest_timestamp", ")", ")", "# Select candidates for deletion.", "candidates", "=", "["...
Delete all older duplicates. Only keeps the subset sharing the most recent timestamp.
[ "Delete", "all", "older", "duplicates", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L228-L247
26,596
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_oldest
def delete_oldest(self): """ Delete all the oldest duplicates. Keeps all mail of the duplicate set but those sharing the oldest timestamp. """ logger.info( "Deleting all mails sharing the oldest {} timestamp...".format( self.oldest_timestamp)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.timestamp == self.oldest_timestamp] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same timestamp." "".format(self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_oldest(self): logger.info( "Deleting all mails sharing the oldest {} timestamp...".format( self.oldest_timestamp)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.timestamp == self.oldest_timestamp] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same timestamp." "".format(self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_oldest", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails sharing the oldest {} timestamp...\"", ".", "format", "(", "self", ".", "oldest_timestamp", ")", ")", "# Select candidates for deletion.", "candidates", "=", "[", "mail", ...
Delete all the oldest duplicates. Keeps all mail of the duplicate set but those sharing the oldest timestamp.
[ "Delete", "all", "the", "oldest", "duplicates", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L249-L270
26,597
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_bigger
def delete_bigger(self): """ Delete all bigger duplicates. Only keeps the subset sharing the smallest size. """ logger.info( "Deleting all mails strictly bigger than {} bytes...".format( self.smallest_size)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.size > self.smallest_size] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same size." "".format(self.size)) logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_bigger(self): logger.info( "Deleting all mails strictly bigger than {} bytes...".format( self.smallest_size)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.size > self.smallest_size] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same size." "".format(self.size)) logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_bigger", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails strictly bigger than {} bytes...\"", ".", "format", "(", "self", ".", "smallest_size", ")", ")", "# Select candidates for deletion.", "candidates", "=", "[", "mail", "for"...
Delete all bigger duplicates. Only keeps the subset sharing the smallest size.
[ "Delete", "all", "bigger", "duplicates", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L361-L380
26,598
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_biggest
def delete_biggest(self): """ Delete all the biggest duplicates. Keeps all mail of the duplicate set but those sharing the biggest size. """ logger.info( "Deleting all mails sharing the biggest size of {} bytes..." "".format(self.biggest_size)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.size == self.biggest_size] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same size." "".format(self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_biggest(self): logger.info( "Deleting all mails sharing the biggest size of {} bytes..." "".format(self.biggest_size)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.size == self.biggest_size] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same size." "".format(self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_biggest", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails sharing the biggest size of {} bytes...\"", "\"\"", ".", "format", "(", "self", ".", "biggest_size", ")", ")", "# Select candidates for deletion.", "candidates", "=", "[", ...
Delete all the biggest duplicates. Keeps all mail of the duplicate set but those sharing the biggest size.
[ "Delete", "all", "the", "biggest", "duplicates", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L382-L403
26,599
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_matching_path
def delete_matching_path(self): """ Delete all duplicates whose file path match the regexp. """ logger.info( "Deleting all mails with file path matching the {} regexp..." "".format(self.conf.regexp.pattern)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if re.search(self.conf.regexp, mail.path)] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails matches the rexexp.".format( self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_matching_path(self): logger.info( "Deleting all mails with file path matching the {} regexp..." "".format(self.conf.regexp.pattern)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if re.search(self.conf.regexp, mail.path)] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails matches the rexexp.".format( self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_matching_path", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails with file path matching the {} regexp...\"", "\"\"", ".", "format", "(", "self", ".", "conf", ".", "regexp", ".", "pattern", ")", ")", "# Select candidates for dele...
Delete all duplicates whose file path match the regexp.
[ "Delete", "all", "duplicates", "whose", "file", "path", "match", "the", "regexp", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L405-L422