repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
pytroll/trollimage
trollimage/colormap.py
colorbar
def colorbar(height, length, colormap): """Return the channels of a colorbar. """ cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1)) cbar = (cbar * (colormap.values.max() - colormap.values.min()) + colormap.values.min()) return colormap.colorize(cbar)
python
def colorbar(height, length, colormap): """Return the channels of a colorbar. """ cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1)) cbar = (cbar * (colormap.values.max() - colormap.values.min()) + colormap.values.min()) return colormap.colorize(cbar)
Return the channels of a colorbar.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colormap.py#L445-L452
pytroll/trollimage
trollimage/colormap.py
palettebar
def palettebar(height, length, colormap): """Return the channels of a palettebar. """ cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1)) cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min()) + colormap.values.min()) return colormap.palettize(cbar)
python
def palettebar(height, length, colormap): """Return the channels of a palettebar. """ cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1)) cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min()) + colormap.values.min()) return colormap.palettize(cbar)
Return the channels of a palettebar.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colormap.py#L455-L462
pytroll/trollimage
trollimage/colormap.py
Colormap.set_range
def set_range(self, min_val, max_val): """Set the range of the colormap to [*min_val*, *max_val*] """ if min_val > max_val: max_val, min_val = min_val, max_val self.values = (((self.values * 1.0 - self.values.min()) / (self.values.max() - self.values.m...
python
def set_range(self, min_val, max_val): """Set the range of the colormap to [*min_val*, *max_val*] """ if min_val > max_val: max_val, min_val = min_val, max_val self.values = (((self.values * 1.0 - self.values.min()) / (self.values.max() - self.values.m...
Set the range of the colormap to [*min_val*, *max_val*]
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colormap.py#L120-L127
pytroll/trollimage
trollimage/colormap.py
Colormap.to_rio
def to_rio(self): """Converts the colormap to a rasterio colormap. """ self.colors = (((self.colors * 1.0 - self.colors.min()) / (self.colors.max() - self.colors.min())) * 255) return dict(zip(self.values, tuple(map(tuple, self.colors))))
python
def to_rio(self): """Converts the colormap to a rasterio colormap. """ self.colors = (((self.colors * 1.0 - self.colors.min()) / (self.colors.max() - self.colors.min())) * 255) return dict(zip(self.values, tuple(map(tuple, self.colors))))
Converts the colormap to a rasterio colormap.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colormap.py#L129-L134
edx/django-user-tasks
user_tasks/views.py
StatusViewSet.cancel
def cancel(self, request, *args, **kwargs): # pylint: disable=unused-argument """ Cancel the task associated with the specified status record. Arguments: request (Request): A POST including a task status record ID Returns ------- Response: A JSON respon...
python
def cancel(self, request, *args, **kwargs): # pylint: disable=unused-argument """ Cancel the task associated with the specified status record. Arguments: request (Request): A POST including a task status record ID Returns ------- Response: A JSON respon...
Cancel the task associated with the specified status record. Arguments: request (Request): A POST including a task status record ID Returns ------- Response: A JSON response indicating whether the cancellation succeeded or not
https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/user_tasks/views.py#L61-L76
edx/django-user-tasks
schema/views.py
swagger
def swagger(request): # pylint: disable=unused-argument """ Render Swagger UI and the underlying Open API schema JSON file. """ generator = schemas.SchemaGenerator(title='django-user-tasks REST API') return response.Response(generator.get_schema())
python
def swagger(request): # pylint: disable=unused-argument """ Render Swagger UI and the underlying Open API schema JSON file. """ generator = schemas.SchemaGenerator(title='django-user-tasks REST API') return response.Response(generator.get_schema())
Render Swagger UI and the underlying Open API schema JSON file.
https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/schema/views.py#L39-L44
edx/django-user-tasks
schema/views.py
ConditionalOpenAPIRenderer.render
def render(self, data, accepted_media_type=None, renderer_context=None): """ Render the appropriate Open API JSON file. """ if 'SWAGGER_JSON_PATH' in os.environ: with io.open(os.environ['SWAGGER_JSON_PATH'], 'rb') as f: return f.read() else: ...
python
def render(self, data, accepted_media_type=None, renderer_context=None): """ Render the appropriate Open API JSON file. """ if 'SWAGGER_JSON_PATH' in os.environ: with io.open(os.environ['SWAGGER_JSON_PATH'], 'rb') as f: return f.read() else: ...
Render the appropriate Open API JSON file.
https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/schema/views.py#L26-L34
edx/django-user-tasks
user_tasks/rules.py
add_rules
def add_rules(): """ Use the rules provided in this module to implement authorization checks for the ``django-user-tasks`` models. These rules allow only superusers and the user who triggered a task to view its status or artifacts, cancel the task, or delete the status information and all its related a...
python
def add_rules(): """ Use the rules provided in this module to implement authorization checks for the ``django-user-tasks`` models. These rules allow only superusers and the user who triggered a task to view its status or artifacts, cancel the task, or delete the status information and all its related a...
Use the rules provided in this module to implement authorization checks for the ``django-user-tasks`` models. These rules allow only superusers and the user who triggered a task to view its status or artifacts, cancel the task, or delete the status information and all its related artifacts. Only superusers ar...
https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/user_tasks/rules.py#L64-L78
edx/django-user-tasks
user_tasks/filters.py
ArtifactFilterBackend.filter_queryset
def filter_queryset(self, request, queryset, view): """ Filter out any artifacts which the requesting user does not have permission to view. """ if request.user.is_superuser: return queryset return queryset.filter(status__user=request.user)
python
def filter_queryset(self, request, queryset, view): """ Filter out any artifacts which the requesting user does not have permission to view. """ if request.user.is_superuser: return queryset return queryset.filter(status__user=request.user)
Filter out any artifacts which the requesting user does not have permission to view.
https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/user_tasks/filters.py#L20-L26
pytroll/trollimage
trollimage/utilities.py
_text_to_rgb
def _text_to_rgb(value,norm=False,cat=1, tot=1,offset=0.5,hex=False): ''' _text_to_rgb takes as input a string composed by 3 values in the range [0,255] and returns a tuple of integers. If the parameters cat and tot are given, the function generates a transparency value for this color and returns a tupl...
python
def _text_to_rgb(value,norm=False,cat=1, tot=1,offset=0.5,hex=False): ''' _text_to_rgb takes as input a string composed by 3 values in the range [0,255] and returns a tuple of integers. If the parameters cat and tot are given, the function generates a transparency value for this color and returns a tupl...
_text_to_rgb takes as input a string composed by 3 values in the range [0,255] and returns a tuple of integers. If the parameters cat and tot are given, the function generates a transparency value for this color and returns a tuple of length 4. tot is the total number of colors in the colormap cat i...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/utilities.py#L29-L49
pytroll/trollimage
trollimage/utilities.py
_make_cmap
def _make_cmap(colors, position=None, bit=False): ''' _make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). _make_cmap returns a cmap with equally spaced colors. ...
python
def _make_cmap(colors, position=None, bit=False): ''' _make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). _make_cmap returns a cmap with equally spaced colors. ...
_make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). _make_cmap returns a cmap with equally spaced colors. Arrange your tuples so that the first color is the lowest va...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/utilities.py#L52-L73
pytroll/trollimage
trollimage/utilities.py
cmap_from_text
def cmap_from_text(filename, norm=False, transparency=False, hex=False): ''' cmap_from_text takes as input a file that contains a colormap in text format composed by lines with 3 values in the range [0,255] or [00,FF] and returns a tuple of integers. If the parameters cat and tot are given, the func...
python
def cmap_from_text(filename, norm=False, transparency=False, hex=False): ''' cmap_from_text takes as input a file that contains a colormap in text format composed by lines with 3 values in the range [0,255] or [00,FF] and returns a tuple of integers. If the parameters cat and tot are given, the func...
cmap_from_text takes as input a file that contains a colormap in text format composed by lines with 3 values in the range [0,255] or [00,FF] and returns a tuple of integers. If the parameters cat and tot are given, the function generates a transparency value for this color and returns a tuple of length ...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/utilities.py#L76-L97
pytroll/trollimage
trollimage/utilities.py
_image2array
def _image2array(filepath): ''' Utility function that converts an image file in 3 np arrays that can be fed into geo_image.GeoImage in order to generate a PyTROLL GeoImage object. ''' im = Pimage.open(filepath).convert('RGB') (width, height) = im.size _r = np.array(list(im.getdata(0)))/2...
python
def _image2array(filepath): ''' Utility function that converts an image file in 3 np arrays that can be fed into geo_image.GeoImage in order to generate a PyTROLL GeoImage object. ''' im = Pimage.open(filepath).convert('RGB') (width, height) = im.size _r = np.array(list(im.getdata(0)))/2...
Utility function that converts an image file in 3 np arrays that can be fed into geo_image.GeoImage in order to generate a PyTROLL GeoImage object.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/utilities.py#L100-L114
pytroll/trollimage
trollimage/image.py
check_image_format
def check_image_format(fformat): """Check that *fformat* is valid """ cases = {"jpg": "jpeg", "jpeg": "jpeg", "tif": "tiff", "tiff": "tif", "pgm": "ppm", "pbm": "ppm", "ppm": "ppm", "bmp": "bmp", "dib": "...
python
def check_image_format(fformat): """Check that *fformat* is valid """ cases = {"jpg": "jpeg", "jpeg": "jpeg", "tif": "tiff", "tiff": "tif", "pgm": "ppm", "pbm": "ppm", "ppm": "ppm", "bmp": "bmp", "dib": "...
Check that *fformat* is valid
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L61-L86
pytroll/trollimage
trollimage/image.py
_is_pair
def _is_pair(item): """Check if an item is a pair (tuple of size 2). """ return (isinstance(item, (list, tuple, set)) and len(item) == 2 and not isinstance(item[0], (list, tuple, set)) and not isinstance(item[1], (list, tuple, set)))
python
def _is_pair(item): """Check if an item is a pair (tuple of size 2). """ return (isinstance(item, (list, tuple, set)) and len(item) == 2 and not isinstance(item[0], (list, tuple, set)) and not isinstance(item[1], (list, tuple, set)))
Check if an item is a pair (tuple of size 2).
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L1121-L1127
pytroll/trollimage
trollimage/image.py
ycbcr2rgb
def ycbcr2rgb(y__, cb_, cr_): """Convert the three YCbCr channels to RGB channels. """ kb_ = 0.114 kr_ = 0.299 r__ = 2 * cr_ / (1 - kr_) + y__ b__ = 2 * cb_ / (1 - kb_) + y__ g__ = (y__ - kr_ * r__ - kb_ * b__) / (1 - kr_ - kb_) return r__, g__, b__
python
def ycbcr2rgb(y__, cb_, cr_): """Convert the three YCbCr channels to RGB channels. """ kb_ = 0.114 kr_ = 0.299 r__ = 2 * cr_ / (1 - kr_) + y__ b__ = 2 * cb_ / (1 - kb_) + y__ g__ = (y__ - kr_ * r__ - kb_ * b__) / (1 - kr_ - kb_) return r__, g__, b__
Convert the three YCbCr channels to RGB channels.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L1136-L1147
pytroll/trollimage
trollimage/image.py
Image._add_channel
def _add_channel(self, chn, color_min, color_max): """Adds a channel to the image object """ if isinstance(chn, np.ma.core.MaskedArray): chn_data = chn.data chn_mask = chn.mask else: chn_data = np.array(chn) chn_mask = False scaled ...
python
def _add_channel(self, chn, color_min, color_max): """Adds a channel to the image object """ if isinstance(chn, np.ma.core.MaskedArray): chn_data = chn.data chn_mask = chn.mask else: chn_data = np.array(chn) chn_mask = False scaled ...
Adds a channel to the image object
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L221-L232
pytroll/trollimage
trollimage/image.py
Image._finalize
def _finalize(self, dtype=np.uint8): """Finalize the image, that is put it in RGB mode, and set the channels in unsigned 8bit format ([0,255] range) (if the *dtype* doesn't say otherwise). """ channels = [] if self.mode == "P": self.convert("RGB") if s...
python
def _finalize(self, dtype=np.uint8): """Finalize the image, that is put it in RGB mode, and set the channels in unsigned 8bit format ([0,255] range) (if the *dtype* doesn't say otherwise). """ channels = [] if self.mode == "P": self.convert("RGB") if s...
Finalize the image, that is put it in RGB mode, and set the channels in unsigned 8bit format ([0,255] range) (if the *dtype* doesn't say otherwise).
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L234-L261
pytroll/trollimage
trollimage/image.py
Image.is_empty
def is_empty(self): """Checks for an empty image. """ if(((self.channels == []) and (not self.shape == (0, 0))) or ((not self.channels == []) and (self.shape == (0, 0)))): raise RuntimeError("Channels-shape mismatch.") return self.channels == [] and self.shape == (...
python
def is_empty(self): """Checks for an empty image. """ if(((self.channels == []) and (not self.shape == (0, 0))) or ((not self.channels == []) and (self.shape == (0, 0)))): raise RuntimeError("Channels-shape mismatch.") return self.channels == [] and self.shape == (...
Checks for an empty image.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L263-L269
pytroll/trollimage
trollimage/image.py
Image.pil_image
def pil_image(self): """Return a PIL image from the current image. """ channels, fill_value = self._finalize() if self.is_empty(): return Pil.new(self.mode, (0, 0)) if self.mode == "L": if fill_value is not None: img = Pil.fromarray(chann...
python
def pil_image(self): """Return a PIL image from the current image. """ channels, fill_value = self._finalize() if self.is_empty(): return Pil.new(self.mode, (0, 0)) if self.mode == "L": if fill_value is not None: img = Pil.fromarray(chann...
Return a PIL image from the current image.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L276-L357
pytroll/trollimage
trollimage/image.py
Image.save
def save(self, filename, compression=6, fformat=None, thumbnail_name=None, thumbnail_size=None): """Save the image to the given *filename*. For some formats like jpg and png, the work is delegated to :meth:`pil_save`, which doesn't support the *compression* option. """ ...
python
def save(self, filename, compression=6, fformat=None, thumbnail_name=None, thumbnail_size=None): """Save the image to the given *filename*. For some formats like jpg and png, the work is delegated to :meth:`pil_save`, which doesn't support the *compression* option. """ ...
Save the image to the given *filename*. For some formats like jpg and png, the work is delegated to :meth:`pil_save`, which doesn't support the *compression* option.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L359-L366
pytroll/trollimage
trollimage/image.py
Image.pil_save
def pil_save(self, filename, compression=6, fformat=None, thumbnail_name=None, thumbnail_size=None): """Save the image to the given *filename* using PIL. For now, the compression level [0-9] is ignored, due to PIL's lack of support. See also :meth:`save`. """ # P...
python
def pil_save(self, filename, compression=6, fformat=None, thumbnail_name=None, thumbnail_size=None): """Save the image to the given *filename* using PIL. For now, the compression level [0-9] is ignored, due to PIL's lack of support. See also :meth:`save`. """ # P...
Save the image to the given *filename* using PIL. For now, the compression level [0-9] is ignored, due to PIL's lack of support. See also :meth:`save`.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L368-L402
pytroll/trollimage
trollimage/image.py
Image._pngmeta
def _pngmeta(self): """It will return GeoImage.tags as a PNG metadata object. Inspired by: public domain, Nick Galbreath http://blog.modp.com/2007/08/python-pil-and-png-metadata-take-2.html """ reserved = ('interlace', 'gamma', 'dpi', 'transparency', 'aspect') t...
python
def _pngmeta(self): """It will return GeoImage.tags as a PNG metadata object. Inspired by: public domain, Nick Galbreath http://blog.modp.com/2007/08/python-pil-and-png-metadata-take-2.html """ reserved = ('interlace', 'gamma', 'dpi', 'transparency', 'aspect') t...
It will return GeoImage.tags as a PNG metadata object. Inspired by: public domain, Nick Galbreath http://blog.modp.com/2007/08/python-pil-and-png-metadata-take-2.html
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L404-L427
pytroll/trollimage
trollimage/image.py
Image.putalpha
def putalpha(self, alpha): """Adds an *alpha* channel to the current image, or replaces it with *alpha* if it already exists. """ alpha = np.ma.array(alpha) if(not (alpha.shape[0] == 0 and self.shape[0] == 0) and alpha.shape != self.shape): ...
python
def putalpha(self, alpha): """Adds an *alpha* channel to the current image, or replaces it with *alpha* if it already exists. """ alpha = np.ma.array(alpha) if(not (alpha.shape[0] == 0 and self.shape[0] == 0) and alpha.shape != self.shape): ...
Adds an *alpha* channel to the current image, or replaces it with *alpha* if it already exists.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L429-L442
pytroll/trollimage
trollimage/image.py
Image._rgb2ycbcr
def _rgb2ycbcr(self, mode): """Convert the image from RGB mode to YCbCr.""" self._check_modes(("RGB", "RGBA")) (self.channels[0], self.channels[1], self.channels[2]) = \ rgb2ycbcr(self.channels[0], self.channels[1], self.channels[2]) ...
python
def _rgb2ycbcr(self, mode): """Convert the image from RGB mode to YCbCr.""" self._check_modes(("RGB", "RGBA")) (self.channels[0], self.channels[1], self.channels[2]) = \ rgb2ycbcr(self.channels[0], self.channels[1], self.channels[2]) ...
Convert the image from RGB mode to YCbCr.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L444-L459
pytroll/trollimage
trollimage/image.py
Image._ycbcr2rgb
def _ycbcr2rgb(self, mode): """Convert the image from YCbCr mode to RGB. """ self._check_modes(("YCbCr", "YCbCrA")) (self.channels[0], self.channels[1], self.channels[2]) = \ ycbcr2rgb(self.channels[0], self.channels[1], self.chan...
python
def _ycbcr2rgb(self, mode): """Convert the image from YCbCr mode to RGB. """ self._check_modes(("YCbCr", "YCbCrA")) (self.channels[0], self.channels[1], self.channels[2]) = \ ycbcr2rgb(self.channels[0], self.channels[1], self.chan...
Convert the image from YCbCr mode to RGB.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L461-L477
pytroll/trollimage
trollimage/image.py
Image._to_p
def _to_p(self, mode): """Convert the image to P or PA mode. """ if self.mode.endswith("A"): chans = self.channels[:-1] alpha = self.channels[-1] self._secondary_mode = self.mode[:-1] else: chans = self.channels alpha = None ...
python
def _to_p(self, mode): """Convert the image to P or PA mode. """ if self.mode.endswith("A"): chans = self.channels[:-1] alpha = self.channels[-1] self._secondary_mode = self.mode[:-1] else: chans = self.channels alpha = None ...
Convert the image to P or PA mode.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L479-L537
pytroll/trollimage
trollimage/image.py
Image._from_p
def _from_p(self, mode): """Convert the image from P or PA mode. """ self._check_modes(("P", "PA")) if self.mode.endswith("A"): alpha = self.channels[-1] else: alpha = None chans = [] cdfs = [] color_chan = self.channels[0] ...
python
def _from_p(self, mode): """Convert the image from P or PA mode. """ self._check_modes(("P", "PA")) if self.mode.endswith("A"): alpha = self.channels[-1] else: alpha = None chans = [] cdfs = [] color_chan = self.channels[0] ...
Convert the image from P or PA mode.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L539-L579
pytroll/trollimage
trollimage/image.py
Image._l2rgb
def _l2rgb(self, mode): """Convert from L (black and white) to RGB. """ self._check_modes(("L", "LA")) self.channels.append(self.channels[0].copy()) self.channels.append(self.channels[0].copy()) if self.fill_value is not None: self.fill_value = self.fill_value...
python
def _l2rgb(self, mode): """Convert from L (black and white) to RGB. """ self._check_modes(("L", "LA")) self.channels.append(self.channels[0].copy()) self.channels.append(self.channels[0].copy()) if self.fill_value is not None: self.fill_value = self.fill_value...
Convert from L (black and white) to RGB.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L590-L601
pytroll/trollimage
trollimage/image.py
Image._rgb2l
def _rgb2l(self, mode): """Convert from RGB to monochrome L. """ self._check_modes(("RGB", "RGBA")) kb_ = 0.114 kr_ = 0.299 r__ = self.channels[0] g__ = self.channels[1] b__ = self.channels[2] y__ = kr_ * r__ + (1 - kr_ - kb_) * g__ + kb_ * b__ ...
python
def _rgb2l(self, mode): """Convert from RGB to monochrome L. """ self._check_modes(("RGB", "RGBA")) kb_ = 0.114 kr_ = 0.299 r__ = self.channels[0] g__ = self.channels[1] b__ = self.channels[2] y__ = kr_ * r__ + (1 - kr_ - kb_) * g__ + kb_ * b__ ...
Convert from RGB to monochrome L.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L603-L625
pytroll/trollimage
trollimage/image.py
Image._ycbcr2l
def _ycbcr2l(self, mode): """Convert from YCbCr to L. """ self._check_modes(("YCbCr", "YCbCrA")) self.channels = [self.channels[0]] + self.channels[3:] if self.fill_value is not None: self.fill_value = [self.fill_value[0]] + self.fill_value[3:] self.mode = mo...
python
def _ycbcr2l(self, mode): """Convert from YCbCr to L. """ self._check_modes(("YCbCr", "YCbCrA")) self.channels = [self.channels[0]] + self.channels[3:] if self.fill_value is not None: self.fill_value = [self.fill_value[0]] + self.fill_value[3:] self.mode = mo...
Convert from YCbCr to L.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L627-L635
pytroll/trollimage
trollimage/image.py
Image._l2ycbcr
def _l2ycbcr(self, mode): """Convert from L to YCbCr. """ self._check_modes(("L", "LA")) luma = self.channels[0] zeros = np.ma.zeros(luma.shape) zeros.mask = luma.mask self.channels = [luma, zeros, zeros] + self.channels[1:] if self.fill_value is not No...
python
def _l2ycbcr(self, mode): """Convert from L to YCbCr. """ self._check_modes(("L", "LA")) luma = self.channels[0] zeros = np.ma.zeros(luma.shape) zeros.mask = luma.mask self.channels = [luma, zeros, zeros] + self.channels[1:] if self.fill_value is not No...
Convert from L to YCbCr.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L637-L651
pytroll/trollimage
trollimage/image.py
Image.convert
def convert(self, mode): """Convert the current image to the given *mode*. See :class:`Image` for a list of available modes. """ if mode == self.mode: return if mode not in ["L", "LA", "RGB", "RGBA", "YCbCr", "YCbCrA", "P", "PA"]: ...
python
def convert(self, mode): """Convert the current image to the given *mode*. See :class:`Image` for a list of available modes. """ if mode == self.mode: return if mode not in ["L", "LA", "RGB", "RGBA", "YCbCr", "YCbCrA", "P", "PA"]: ...
Convert the current image to the given *mode*. See :class:`Image` for a list of available modes.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L653-L718
pytroll/trollimage
trollimage/image.py
Image.clip
def clip(self, channels=True): """Limit the values of the array to the default [0,1] range. *channels* says which channels should be clipped.""" if not isinstance(channels, (tuple, list)): channels = [channels] * len(self.channels) for i in range(len(self.channels)): ...
python
def clip(self, channels=True): """Limit the values of the array to the default [0,1] range. *channels* says which channels should be clipped.""" if not isinstance(channels, (tuple, list)): channels = [channels] * len(self.channels) for i in range(len(self.channels)): ...
Limit the values of the array to the default [0,1] range. *channels* says which channels should be clipped.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L720-L728
pytroll/trollimage
trollimage/image.py
Image.resize
def resize(self, shape): """Resize the image to the given *shape* tuple, in place. For zooming, nearest neighbour method is used, while for shrinking, decimation is used. Therefore, *shape* must be a multiple or a divisor of the image shape. """ if self.is_empty(): ...
python
def resize(self, shape): """Resize the image to the given *shape* tuple, in place. For zooming, nearest neighbour method is used, while for shrinking, decimation is used. Therefore, *shape* must be a multiple or a divisor of the image shape. """ if self.is_empty(): ...
Resize the image to the given *shape* tuple, in place. For zooming, nearest neighbour method is used, while for shrinking, decimation is used. Therefore, *shape* must be a multiple or a divisor of the image shape.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L730-L781
pytroll/trollimage
trollimage/image.py
Image.replace_luminance
def replace_luminance(self, luminance): """Replace the Y channel of the image by the array *luminance*. If the image is not in YCbCr mode, it is converted automatically to and from that mode. """ if self.is_empty(): return if luminance.shape != self.channels[...
python
def replace_luminance(self, luminance): """Replace the Y channel of the image by the array *luminance*. If the image is not in YCbCr mode, it is converted automatically to and from that mode. """ if self.is_empty(): return if luminance.shape != self.channels[...
Replace the Y channel of the image by the array *luminance*. If the image is not in YCbCr mode, it is converted automatically to and from that mode.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L783-L809
pytroll/trollimage
trollimage/image.py
Image.enhance
def enhance(self, inverse=False, gamma=1.0, stretch="no", stretch_parameters=None, **kwargs): """Image enhancement function. It applies **in this order** inversion, gamma correction, and stretching to the current image, with parameters *inverse* (see :meth:`Image.invert`), *gamma...
python
def enhance(self, inverse=False, gamma=1.0, stretch="no", stretch_parameters=None, **kwargs): """Image enhancement function. It applies **in this order** inversion, gamma correction, and stretching to the current image, with parameters *inverse* (see :meth:`Image.invert`), *gamma...
Image enhancement function. It applies **in this order** inversion, gamma correction, and stretching to the current image, with parameters *inverse* (see :meth:`Image.invert`), *gamma* (see :meth:`Image.gamma`), and *stretch* (see :meth:`Image.stretch`).
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L811-L824
pytroll/trollimage
trollimage/image.py
Image.gamma
def gamma(self, gamma=1.0): """Apply gamma correction to the channels of the image. If *gamma* is a tuple, then it should have as many elements as the channels of the image, and the gamma correction is applied elementwise. If *gamma* is a number, the same gamma correction is applied on e...
python
def gamma(self, gamma=1.0): """Apply gamma correction to the channels of the image. If *gamma* is a tuple, then it should have as many elements as the channels of the image, and the gamma correction is applied elementwise. If *gamma* is a number, the same gamma correction is applied on e...
Apply gamma correction to the channels of the image. If *gamma* is a tuple, then it should have as many elements as the channels of the image, and the gamma correction is applied elementwise. If *gamma* is a number, the same gamma correction is applied on every channel, if there are seve...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L826-L867
pytroll/trollimage
trollimage/image.py
Image.stretch
def stretch(self, stretch="crude", **kwargs): """Apply stretching to the current image. The value of *stretch* sets the type of stretching applied. The values "histogram", "linear", "crude" (or "crude-stretch") perform respectively histogram equalization, contrast stretching (with 5% cut...
python
def stretch(self, stretch="crude", **kwargs): """Apply stretching to the current image. The value of *stretch* sets the type of stretching applied. The values "histogram", "linear", "crude" (or "crude-stretch") perform respectively histogram equalization, contrast stretching (with 5% cut...
Apply stretching to the current image. The value of *stretch* sets the type of stretching applied. The values "histogram", "linear", "crude" (or "crude-stretch") perform respectively histogram equalization, contrast stretching (with 5% cutoff on both sides), and contrast stretching witho...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L869-L913
pytroll/trollimage
trollimage/image.py
Image.invert
def invert(self, invert=True): """Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if *invert* is true (default). Note: 'Inverting' means that black becomes white, and vice-versa, n...
python
def invert(self, invert=True): """Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if *invert* is true (default). Note: 'Inverting' means that black becomes white, and vice-versa, n...
Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if *invert* is true (default). Note: 'Inverting' means that black becomes white, and vice-versa, not that the values are negated !
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L915-L933
pytroll/trollimage
trollimage/image.py
Image.stretch_hist_equalize
def stretch_hist_equalize(self, ch_nb): """Stretch the current image's colors by performing histogram equalization on channel *ch_nb*. """ logger.info("Perform a histogram equalized contrast stretch.") if(self.channels[ch_nb].size == np.ma.count_masked(self.channels[c...
python
def stretch_hist_equalize(self, ch_nb): """Stretch the current image's colors by performing histogram equalization on channel *ch_nb*. """ logger.info("Perform a histogram equalized contrast stretch.") if(self.channels[ch_nb].size == np.ma.count_masked(self.channels[c...
Stretch the current image's colors by performing histogram equalization on channel *ch_nb*.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L935-L961
pytroll/trollimage
trollimage/image.py
Image.stretch_logarithmic
def stretch_logarithmic(self, ch_nb, factor=100.): """Move data into range [1:factor] and do a normalized logarithmic enhancement. """ logger.debug("Perform a logarithmic contrast stretch.") if ((self.channels[ch_nb].size == np.ma.count_masked(self.channels[ch_nb])) ...
python
def stretch_logarithmic(self, ch_nb, factor=100.): """Move data into range [1:factor] and do a normalized logarithmic enhancement. """ logger.debug("Perform a logarithmic contrast stretch.") if ((self.channels[ch_nb].size == np.ma.count_masked(self.channels[ch_nb])) ...
Move data into range [1:factor] and do a normalized logarithmic enhancement.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L963-L982
pytroll/trollimage
trollimage/image.py
Image.stretch_linear
def stretch_linear(self, ch_nb, cutoffs=(0.005, 0.005)): """Stretch linearly the contrast of the current image on channel *ch_nb*, using *cutoffs* for left and right trimming. """ logger.debug("Perform a linear contrast stretch.") if((self.channels[ch_nb].size == np....
python
def stretch_linear(self, ch_nb, cutoffs=(0.005, 0.005)): """Stretch linearly the contrast of the current image on channel *ch_nb*, using *cutoffs* for left and right trimming. """ logger.debug("Perform a linear contrast stretch.") if((self.channels[ch_nb].size == np....
Stretch linearly the contrast of the current image on channel *ch_nb*, using *cutoffs* for left and right trimming.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L984-L1014
pytroll/trollimage
trollimage/image.py
Image.crude_stretch
def crude_stretch(self, ch_nb, min_stretch=None, max_stretch=None): """Perform simple linear stretching (without any cutoff) on the channel *ch_nb* of the current image and normalize to the [0,1] range.""" if min_stretch is None: min_stretch = self.channels[ch_nb].min() if m...
python
def crude_stretch(self, ch_nb, min_stretch=None, max_stretch=None): """Perform simple linear stretching (without any cutoff) on the channel *ch_nb* of the current image and normalize to the [0,1] range.""" if min_stretch is None: min_stretch = self.channels[ch_nb].min() if m...
Perform simple linear stretching (without any cutoff) on the channel *ch_nb* of the current image and normalize to the [0,1] range.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L1016-L1039
pytroll/trollimage
trollimage/image.py
Image.colorize
def colorize(self, colormap): """Colorize the current image using *colormap*. Works only on"L" or "LA" images. """ if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") if self.mode == "LA": alpha = self.channels[1] ...
python
def colorize(self, colormap): """Colorize the current image using *colormap*. Works only on"L" or "LA" images. """ if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") if self.mode == "LA": alpha = self.channels[1] ...
Colorize the current image using *colormap*. Works only on"L" or "LA" images.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L1062-L1078
pytroll/trollimage
trollimage/image.py
Image.palettize
def palettize(self, colormap): """Palettize the current image using *colormap*. Works only on"L" or "LA" images. """ if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") self.channels[0], self.palette = colormap.palettize(self.ch...
python
def palettize(self, colormap): """Palettize the current image using *colormap*. Works only on"L" or "LA" images. """ if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") self.channels[0], self.palette = colormap.palettize(self.ch...
Palettize the current image using *colormap*. Works only on"L" or "LA" images.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L1080-L1091
pytroll/trollimage
trollimage/colorspaces.py
lab2xyz
def lab2xyz(l__, a__, b__): """Convert L*a*b* to XYZ, L*a*b* expressed within [0, 1]. """ def f_inv(arr): """Inverse of the f function. """ return np.where(arr > 6.0/29.0, arr ** 3, 3 * (6.0 / 29.0) * (6.0 / 29.0) * (arr - 4.0 / 29.0)...
python
def lab2xyz(l__, a__, b__): """Convert L*a*b* to XYZ, L*a*b* expressed within [0, 1]. """ def f_inv(arr): """Inverse of the f function. """ return np.where(arr > 6.0/29.0, arr ** 3, 3 * (6.0 / 29.0) * (6.0 / 29.0) * (arr - 4.0 / 29.0)...
Convert L*a*b* to XYZ, L*a*b* expressed within [0, 1].
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colorspaces.py#L28-L45
pytroll/trollimage
trollimage/colorspaces.py
xyz2lab
def xyz2lab(x__, y__, z__): """Convert XYZ to L*a*b*. """ def f__(arr): """f__ function """ return np.where(arr > 216.0 / 24389.0, arr ** (1.0/3.0), (1.0 / 3.0) * (29.0 / 6.0) * (29.0 / 6.0) * arr + 4.0 / 29.0)...
python
def xyz2lab(x__, y__, z__): """Convert XYZ to L*a*b*. """ def f__(arr): """f__ function """ return np.where(arr > 216.0 / 24389.0, arr ** (1.0/3.0), (1.0 / 3.0) * (29.0 / 6.0) * (29.0 / 6.0) * arr + 4.0 / 29.0)...
Convert XYZ to L*a*b*.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colorspaces.py#L47-L63
pytroll/trollimage
trollimage/colorspaces.py
hcl2lab
def hcl2lab(h__, c__, l__): """HCL to L*ab """ h_rad = np.deg2rad(h__) l2_ = l__ * 61 + 9 angle = np.pi / 3.0 - h_rad r__ = (l__ * 311 + 125) * c__ a__ = np.sin(angle) * r__ b__ = np.cos(angle) * r__ return l2_, a__, b__
python
def hcl2lab(h__, c__, l__): """HCL to L*ab """ h_rad = np.deg2rad(h__) l2_ = l__ * 61 + 9 angle = np.pi / 3.0 - h_rad r__ = (l__ * 311 + 125) * c__ a__ = np.sin(angle) * r__ b__ = np.cos(angle) * r__ return l2_, a__, b__
HCL to L*ab
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colorspaces.py#L66-L75
pytroll/trollimage
trollimage/colorspaces.py
lab2hcl
def lab2hcl(l__, a__, b__): """L*a*b* to HCL """ l2_ = (l__ - 9) / 61.0 r__ = np.sqrt(a__*a__ + b__*b__) s__ = r__ / (l2_ * 311 + 125) angle = np.arctan2(a__, b__) c__ = np.rad2deg(np.pi / 3 - angle)%360 return c__, s__, l2_
python
def lab2hcl(l__, a__, b__): """L*a*b* to HCL """ l2_ = (l__ - 9) / 61.0 r__ = np.sqrt(a__*a__ + b__*b__) s__ = r__ / (l2_ * 311 + 125) angle = np.arctan2(a__, b__) c__ = np.rad2deg(np.pi / 3 - angle)%360 return c__, s__, l2_
L*a*b* to HCL
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colorspaces.py#L77-L85
pytroll/trollimage
trollimage/colorspaces.py
rgb2xyz
def rgb2xyz(r__, g__, b__): """RGB to XYZ """ r2_ = r__ / 255.0 g2_ = g__ / 255.0 b2_ = b__ / 255.0 def f__(arr): """Forward """ return np.where(arr > 0.04045, ((arr + 0.055) / 1.055) ** 2.4, arr / 12.92) r2_ = f__(r...
python
def rgb2xyz(r__, g__, b__): """RGB to XYZ """ r2_ = r__ / 255.0 g2_ = g__ / 255.0 b2_ = b__ / 255.0 def f__(arr): """Forward """ return np.where(arr > 0.04045, ((arr + 0.055) / 1.055) ** 2.4, arr / 12.92) r2_ = f__(r...
RGB to XYZ
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colorspaces.py#L87-L111
pytroll/trollimage
trollimage/colorspaces.py
xyz2rgb
def xyz2rgb(x__, y__, z__): """XYZ colorspace to RGB """ x2_ = x__ / 100.0 y2_ = y__ / 100.0 z2_ = z__ / 100.0 r__ = x2_ * 3.2406 + y2_ * -1.5372 + z2_ * -0.4986 g__ = x2_ * -0.9689 + y2_ * 1.8758 + z2_ * 0.0415 b__ = x2_ * 0.0557 + y2_ * -0.2040 + z2_ * 1.0570 def finv(arr): ...
python
def xyz2rgb(x__, y__, z__): """XYZ colorspace to RGB """ x2_ = x__ / 100.0 y2_ = y__ / 100.0 z2_ = z__ / 100.0 r__ = x2_ * 3.2406 + y2_ * -1.5372 + z2_ * -0.4986 g__ = x2_ * -0.9689 + y2_ * 1.8758 + z2_ * 0.0415 b__ = x2_ * 0.0557 + y2_ * -0.2040 + z2_ * 1.0570 def finv(arr): ...
XYZ colorspace to RGB
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/colorspaces.py#L113-L131
edx/django-user-tasks
user_tasks/tasks.py
purge_old_user_tasks
def purge_old_user_tasks(): """ Delete any UserTaskStatus and UserTaskArtifact records older than ``settings.USER_TASKS_MAX_AGE``. Intended to be run as a scheduled task. """ limit = now() - settings.USER_TASKS_MAX_AGE # UserTaskArtifacts will also be removed via deletion cascading UserTask...
python
def purge_old_user_tasks(): """ Delete any UserTaskStatus and UserTaskArtifact records older than ``settings.USER_TASKS_MAX_AGE``. Intended to be run as a scheduled task. """ limit = now() - settings.USER_TASKS_MAX_AGE # UserTaskArtifacts will also be removed via deletion cascading UserTask...
Delete any UserTaskStatus and UserTaskArtifact records older than ``settings.USER_TASKS_MAX_AGE``. Intended to be run as a scheduled task.
https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/user_tasks/tasks.py#L110-L118
edx/django-user-tasks
user_tasks/tasks.py
UserTaskMixin.arguments_as_dict
def arguments_as_dict(cls, *args, **kwargs): """ Generate the arguments dictionary provided to :py:meth:`generate_name` and :py:meth:`calculate_total_steps`. This makes it possible to fetch arguments by name regardless of whether they were passed as positional or keyword arguments. Unn...
python
def arguments_as_dict(cls, *args, **kwargs): """ Generate the arguments dictionary provided to :py:meth:`generate_name` and :py:meth:`calculate_total_steps`. This makes it possible to fetch arguments by name regardless of whether they were passed as positional or keyword arguments. Unn...
Generate the arguments dictionary provided to :py:meth:`generate_name` and :py:meth:`calculate_total_steps`. This makes it possible to fetch arguments by name regardless of whether they were passed as positional or keyword arguments. Unnamed positional arguments are provided as a tuple under t...
https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/user_tasks/tasks.py#L62-L71
edx/django-user-tasks
user_tasks/tasks.py
UserTaskMixin.status
def status(self): """ Get the :py:class:`~user_tasks.models.UserTaskStatus` model instance for this UserTaskMixin. """ task_id = self.request.id try: # Most calls are for existing objects, don't waste time # preparing creation arguments unless necessary ...
python
def status(self): """ Get the :py:class:`~user_tasks.models.UserTaskStatus` model instance for this UserTaskMixin. """ task_id = self.request.id try: # Most calls are for existing objects, don't waste time # preparing creation arguments unless necessary ...
Get the :py:class:`~user_tasks.models.UserTaskStatus` model instance for this UserTaskMixin.
https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/user_tasks/tasks.py#L74-L95
pytroll/trollimage
trollimage/xrimage.py
color_interp
def color_interp(data): """Get the color interpretation for this image.""" from rasterio.enums import ColorInterp as ci modes = {'L': [ci.gray], 'LA': [ci.gray, ci.alpha], 'YCbCr': [ci.Y, ci.Cb, ci.Cr], 'YCbCrA': [ci.Y, ci.Cb, ci.Cr, ci.alpha]} try: mode =...
python
def color_interp(data): """Get the color interpretation for this image.""" from rasterio.enums import ColorInterp as ci modes = {'L': [ci.gray], 'LA': [ci.gray, ci.alpha], 'YCbCr': [ci.Y, ci.Cb, ci.Cr], 'YCbCrA': [ci.Y, ci.Cb, ci.Cr, ci.alpha]} try: mode =...
Get the color interpretation for this image.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L141-L165
pytroll/trollimage
trollimage/xrimage.py
XRImage._correct_dims
def _correct_dims(data): """Standardize dimensions to bands, y, and x.""" if not hasattr(data, 'dims'): raise TypeError("Data must have a 'dims' attribute.") # doesn't actually copy the data underneath # we don't want our operations to change the user's data data = d...
python
def _correct_dims(data): """Standardize dimensions to bands, y, and x.""" if not hasattr(data, 'dims'): raise TypeError("Data must have a 'dims' attribute.") # doesn't actually copy the data underneath # we don't want our operations to change the user's data data = d...
Standardize dimensions to bands, y, and x.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L189-L220
pytroll/trollimage
trollimage/xrimage.py
XRImage.save
def save(self, filename, fformat=None, fill_value=None, compute=True, keep_palette=False, cmap=None, **format_kwargs): """Save the image to the given *filename*. Args: filename (str): Output filename fformat (str): File format of output file (optional). Can be ...
python
def save(self, filename, fformat=None, fill_value=None, compute=True, keep_palette=False, cmap=None, **format_kwargs): """Save the image to the given *filename*. Args: filename (str): Output filename fformat (str): File format of output file (optional). Can be ...
Save the image to the given *filename*. Args: filename (str): Output filename fformat (str): File format of output file (optional). Can be one of many image formats supported by the `rasterio` or `PIL` libraries ('jpg', 'png', ...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L227-L274
pytroll/trollimage
trollimage/xrimage.py
XRImage.rio_save
def rio_save(self, filename, fformat=None, fill_value=None, dtype=np.uint8, compute=True, tags=None, keep_palette=False, cmap=None, **format_kwargs): """Save the image using rasterio. Overviews can be added to the file using the `overviews` kwarg, eg::...
python
def rio_save(self, filename, fformat=None, fill_value=None, dtype=np.uint8, compute=True, tags=None, keep_palette=False, cmap=None, **format_kwargs): """Save the image using rasterio. Overviews can be added to the file using the `overviews` kwarg, eg::...
Save the image using rasterio. Overviews can be added to the file using the `overviews` kwarg, eg:: img.rio_save('myfile.tif', overviews=[2, 4, 8, 16])
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L276-L377
pytroll/trollimage
trollimage/xrimage.py
XRImage.pil_save
def pil_save(self, filename, fformat=None, fill_value=None, compute=True, **format_kwargs): """Save the image to the given *filename* using PIL. For now, the compression level [0-9] is ignored, due to PIL's lack of support. See also :meth:`save`. """ fformat = f...
python
def pil_save(self, filename, fformat=None, fill_value=None, compute=True, **format_kwargs): """Save the image to the given *filename* using PIL. For now, the compression level [0-9] is ignored, due to PIL's lack of support. See also :meth:`save`. """ fformat = f...
Save the image to the given *filename* using PIL. For now, the compression level [0-9] is ignored, due to PIL's lack of support. See also :meth:`save`.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L379-L397
pytroll/trollimage
trollimage/xrimage.py
XRImage._create_alpha
def _create_alpha(self, data, fill_value=None): """Create an alpha band DataArray object. If `fill_value` is provided and input data is an integer type then it is used to determine invalid "null" pixels instead of xarray's `isnull` and `notnull` methods. The returned array is 1...
python
def _create_alpha(self, data, fill_value=None): """Create an alpha band DataArray object. If `fill_value` is provided and input data is an integer type then it is used to determine invalid "null" pixels instead of xarray's `isnull` and `notnull` methods. The returned array is 1...
Create an alpha band DataArray object. If `fill_value` is provided and input data is an integer type then it is used to determine invalid "null" pixels instead of xarray's `isnull` and `notnull` methods. The returned array is 1 where data is valid, 0 where invalid.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L424-L445
pytroll/trollimage
trollimage/xrimage.py
XRImage._add_alpha
def _add_alpha(self, data, alpha=None): """Create an alpha channel and concatenate it to the provided data. If ``data`` is an integer type then the alpha band will be scaled to use the smallest (min) value as fully transparent and the largest (max) value as fully opaque. For float types...
python
def _add_alpha(self, data, alpha=None): """Create an alpha channel and concatenate it to the provided data. If ``data`` is an integer type then the alpha band will be scaled to use the smallest (min) value as fully transparent and the largest (max) value as fully opaque. For float types...
Create an alpha channel and concatenate it to the provided data. If ``data`` is an integer type then the alpha band will be scaled to use the smallest (min) value as fully transparent and the largest (max) value as fully opaque. For float types the alpha band spans 0 to 1.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L447-L463
pytroll/trollimage
trollimage/xrimage.py
XRImage._scale_to_dtype
def _scale_to_dtype(self, data, dtype): """Scale provided data to dtype range assuming a 0-1 range. Float input data is assumed to be normalized to a 0 to 1 range. Integer input data is not scaled, only clipped. A float output type is not scaled since both outputs and inputs are assumed...
python
def _scale_to_dtype(self, data, dtype): """Scale provided data to dtype range assuming a 0-1 range. Float input data is assumed to be normalized to a 0 to 1 range. Integer input data is not scaled, only clipped. A float output type is not scaled since both outputs and inputs are assumed...
Scale provided data to dtype range assuming a 0-1 range. Float input data is assumed to be normalized to a 0 to 1 range. Integer input data is not scaled, only clipped. A float output type is not scaled since both outputs and inputs are assumed to be in the 0-1 range already.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L465-L483
pytroll/trollimage
trollimage/xrimage.py
XRImage._check_modes
def _check_modes(self, modes): """Check that the image is in one of the given *modes*, raise an exception otherwise.""" if not isinstance(modes, (tuple, list, set)): modes = [modes] if self.mode not in modes: raise ValueError("Image not in suitable mode, expected: %s, got...
python
def _check_modes(self, modes): """Check that the image is in one of the given *modes*, raise an exception otherwise.""" if not isinstance(modes, (tuple, list, set)): modes = [modes] if self.mode not in modes: raise ValueError("Image not in suitable mode, expected: %s, got...
Check that the image is in one of the given *modes*, raise an exception otherwise.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L485-L490
pytroll/trollimage
trollimage/xrimage.py
XRImage._from_p
def _from_p(self, mode): """Convert the image from P or PA to RGB or RGBA.""" self._check_modes(("P", "PA")) if not self.palette: raise RuntimeError("Can't convert palettized image, missing palette.") pal = np.array(self.palette) pal = da.from_array(pal, chunks=pal.s...
python
def _from_p(self, mode): """Convert the image from P or PA to RGB or RGBA.""" self._check_modes(("P", "PA")) if not self.palette: raise RuntimeError("Can't convert palettized image, missing palette.") pal = np.array(self.palette) pal = da.from_array(pal, chunks=pal.s...
Convert the image from P or PA to RGB or RGBA.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L492-L527
pytroll/trollimage
trollimage/xrimage.py
XRImage._l2rgb
def _l2rgb(self, mode): """Convert from L (black and white) to RGB. """ self._check_modes(("L", "LA")) bands = ["L"] * 3 if mode[-1] == "A": bands.append("A") data = self.data.sel(bands=bands) data["bands"] = list(mode) return data
python
def _l2rgb(self, mode): """Convert from L (black and white) to RGB. """ self._check_modes(("L", "LA")) bands = ["L"] * 3 if mode[-1] == "A": bands.append("A") data = self.data.sel(bands=bands) data["bands"] = list(mode) return data
Convert from L (black and white) to RGB.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L529-L539
pytroll/trollimage
trollimage/xrimage.py
XRImage._finalize
def _finalize(self, fill_value=None, dtype=np.uint8, keep_palette=False, cmap=None): """Wrapper around 'finalize' method for backwards compatibility.""" import warnings warnings.warn("'_finalize' is deprecated, use 'finalize' instead.", DeprecationWarning) return se...
python
def _finalize(self, fill_value=None, dtype=np.uint8, keep_palette=False, cmap=None): """Wrapper around 'finalize' method for backwards compatibility.""" import warnings warnings.warn("'_finalize' is deprecated, use 'finalize' instead.", DeprecationWarning) return se...
Wrapper around 'finalize' method for backwards compatibility.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L586-L591
pytroll/trollimage
trollimage/xrimage.py
XRImage.finalize
def finalize(self, fill_value=None, dtype=np.uint8, keep_palette=False, cmap=None): """Finalize the image to be written to an output file. This adds an alpha band or fills data with a fill_value (if specified). It also scales float data to the output range of the data type (0-255 for ui...
python
def finalize(self, fill_value=None, dtype=np.uint8, keep_palette=False, cmap=None): """Finalize the image to be written to an output file. This adds an alpha band or fills data with a fill_value (if specified). It also scales float data to the output range of the data type (0-255 for ui...
Finalize the image to be written to an output file. This adds an alpha band or fills data with a fill_value (if specified). It also scales float data to the output range of the data type (0-255 for uint8, default). For integer input data this method assumes the data is already scaled to...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L593-L646
pytroll/trollimage
trollimage/xrimage.py
XRImage.pil_image
def pil_image(self, fill_value=None, compute=True): """Return a PIL image from the current image. Args: fill_value (int or float): Value to use for NaN null values. See :meth:`~trollimage.xrimage.XRImage.finalize` for more info. compute (bool): Wh...
python
def pil_image(self, fill_value=None, compute=True): """Return a PIL image from the current image. Args: fill_value (int or float): Value to use for NaN null values. See :meth:`~trollimage.xrimage.XRImage.finalize` for more info. compute (bool): Wh...
Return a PIL image from the current image. Args: fill_value (int or float): Value to use for NaN null values. See :meth:`~trollimage.xrimage.XRImage.finalize` for more info. compute (bool): Whether to return a fully computed PIL.Image obje...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L648-L665
pytroll/trollimage
trollimage/xrimage.py
XRImage.xrify_tuples
def xrify_tuples(self, tup): """Make xarray.DataArray from tuple.""" return xr.DataArray(tup, dims=['bands'], coords={'bands': self.data['bands']})
python
def xrify_tuples(self, tup): """Make xarray.DataArray from tuple.""" return xr.DataArray(tup, dims=['bands'], coords={'bands': self.data['bands']})
Make xarray.DataArray from tuple.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L667-L671
pytroll/trollimage
trollimage/xrimage.py
XRImage.gamma
def gamma(self, gamma=1.0): """Apply gamma correction to the channels of the image. If *gamma* is a tuple, then it should have as many elements as the channels of the image, and the gamma correction is applied elementwise. If *gamma* is a number, the same gamma correction is app...
python
def gamma(self, gamma=1.0): """Apply gamma correction to the channels of the image. If *gamma* is a tuple, then it should have as many elements as the channels of the image, and the gamma correction is applied elementwise. If *gamma* is a number, the same gamma correction is app...
Apply gamma correction to the channels of the image. If *gamma* is a tuple, then it should have as many elements as the channels of the image, and the gamma correction is applied elementwise. If *gamma* is a number, the same gamma correction is applied on every channel, if there ...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L673-L692
pytroll/trollimage
trollimage/xrimage.py
XRImage.stretch
def stretch(self, stretch="crude", **kwargs): """Apply stretching to the current image. The value of *stretch* sets the type of stretching applied. The values "histogram", "linear", "crude" (or "crude-stretch") perform respectively histogram equalization, contrast stretching (with 5% cu...
python
def stretch(self, stretch="crude", **kwargs): """Apply stretching to the current image. The value of *stretch* sets the type of stretching applied. The values "histogram", "linear", "crude" (or "crude-stretch") perform respectively histogram equalization, contrast stretching (with 5% cu...
Apply stretching to the current image. The value of *stretch* sets the type of stretching applied. The values "histogram", "linear", "crude" (or "crude-stretch") perform respectively histogram equalization, contrast stretching (with 5% cutoff on both sides), and contrast stretching with...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L694-L730
pytroll/trollimage
trollimage/xrimage.py
XRImage._compute_quantile
def _compute_quantile(data, dims, cutoffs): """Helper method for stretch_linear. Dask delayed functions need to be non-internal functions (created inside a function) to be serializable on a multi-process scheduler. Quantile requires the data to be loaded since it not supported on ...
python
def _compute_quantile(data, dims, cutoffs): """Helper method for stretch_linear. Dask delayed functions need to be non-internal functions (created inside a function) to be serializable on a multi-process scheduler. Quantile requires the data to be loaded since it not supported on ...
Helper method for stretch_linear. Dask delayed functions need to be non-internal functions (created inside a function) to be serializable on a multi-process scheduler. Quantile requires the data to be loaded since it not supported on dask arrays yet.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L733-L749
pytroll/trollimage
trollimage/xrimage.py
XRImage.stretch_linear
def stretch_linear(self, cutoffs=(0.005, 0.005)): """Stretch linearly the contrast of the current image. Use *cutoffs* for left and right trimming. """ logger.debug("Perform a linear contrast stretch.") logger.debug("Calculate the histogram quantiles: ") logger.debug("L...
python
def stretch_linear(self, cutoffs=(0.005, 0.005)): """Stretch linearly the contrast of the current image. Use *cutoffs* for left and right trimming. """ logger.debug("Perform a linear contrast stretch.") logger.debug("Calculate the histogram quantiles: ") logger.debug("L...
Stretch linearly the contrast of the current image. Use *cutoffs* for left and right trimming.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L751-L780
pytroll/trollimage
trollimage/xrimage.py
XRImage.crude_stretch
def crude_stretch(self, min_stretch=None, max_stretch=None): """Perform simple linear stretching. This is done without any cutoff on the current image and normalizes to the [0,1] range. """ if min_stretch is None: non_band_dims = tuple(x for x in self.data.dims if x ...
python
def crude_stretch(self, min_stretch=None, max_stretch=None): """Perform simple linear stretching. This is done without any cutoff on the current image and normalizes to the [0,1] range. """ if min_stretch is None: non_band_dims = tuple(x for x in self.data.dims if x ...
Perform simple linear stretching. This is done without any cutoff on the current image and normalizes to the [0,1] range.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L782-L809
pytroll/trollimage
trollimage/xrimage.py
XRImage.stretch_hist_equalize
def stretch_hist_equalize(self, approximate=False): """Stretch the current image's colors through histogram equalization. Args: approximate (bool): Use a faster less-accurate percentile calculation. At the time of writing the dask ...
python
def stretch_hist_equalize(self, approximate=False): """Stretch the current image's colors through histogram equalization. Args: approximate (bool): Use a faster less-accurate percentile calculation. At the time of writing the dask ...
Stretch the current image's colors through histogram equalization. Args: approximate (bool): Use a faster less-accurate percentile calculation. At the time of writing the dask version of `percentile` is not as accurate as ...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L811-L856
pytroll/trollimage
trollimage/xrimage.py
XRImage.stretch_logarithmic
def stretch_logarithmic(self, factor=100.): """Move data into range [1:factor] through normalized logarithm.""" logger.debug("Perform a logarithmic contrast stretch.") crange = (0., 1.0) b__ = float(crange[1] - crange[0]) / np.log(factor) c__ = float(crange[0]) def _ban...
python
def stretch_logarithmic(self, factor=100.): """Move data into range [1:factor] through normalized logarithm.""" logger.debug("Perform a logarithmic contrast stretch.") crange = (0., 1.0) b__ = float(crange[1] - crange[0]) / np.log(factor) c__ = float(crange[0]) def _ban...
Move data into range [1:factor] through normalized logarithm.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L858-L883
pytroll/trollimage
trollimage/xrimage.py
XRImage.stretch_weber_fechner
def stretch_weber_fechner(self, k, s0): """Stretch according to the Weber-Fechner law. p = k.ln(S/S0) p is perception, S is the stimulus, S0 is the stimulus threshold (the highest unpercieved stimulus), and k is the factor. """ attrs = self.data.attrs self.data =...
python
def stretch_weber_fechner(self, k, s0): """Stretch according to the Weber-Fechner law. p = k.ln(S/S0) p is perception, S is the stimulus, S0 is the stimulus threshold (the highest unpercieved stimulus), and k is the factor. """ attrs = self.data.attrs self.data =...
Stretch according to the Weber-Fechner law. p = k.ln(S/S0) p is perception, S is the stimulus, S0 is the stimulus threshold (the highest unpercieved stimulus), and k is the factor.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L885-L894
pytroll/trollimage
trollimage/xrimage.py
XRImage.invert
def invert(self, invert=True): """Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if *invert* is true (default). Note: 'Inverting' means that black becomes white, and vice...
python
def invert(self, invert=True): """Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if *invert* is true (default). Note: 'Inverting' means that black becomes white, and vice...
Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if *invert* is true (default). Note: 'Inverting' means that black becomes white, and vice-versa, not that the values are ne...
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L896-L915
pytroll/trollimage
trollimage/xrimage.py
XRImage.merge
def merge(self, img): """Use the provided image as background for the current *img* image, that is if the current image has missing data. """ raise NotImplementedError("This method has not be implemented for " "xarray support.") if self.is_empty(...
python
def merge(self, img): """Use the provided image as background for the current *img* image, that is if the current image has missing data. """ raise NotImplementedError("This method has not be implemented for " "xarray support.") if self.is_empty(...
Use the provided image as background for the current *img* image, that is if the current image has missing data.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L917-L938
pytroll/trollimage
trollimage/xrimage.py
XRImage.colorize
def colorize(self, colormap): """Colorize the current image using `colormap`. .. note:: Works only on "L" or "LA" images. """ if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") if self.mode == "LA": ...
python
def colorize(self, colormap): """Colorize the current image using `colormap`. .. note:: Works only on "L" or "LA" images. """ if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") if self.mode == "LA": ...
Colorize the current image using `colormap`. .. note:: Works only on "L" or "LA" images.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L940-L982
pytroll/trollimage
trollimage/xrimage.py
XRImage.palettize
def palettize(self, colormap): """Palettize the current image using `colormap`. .. note:: Works only on "L" or "LA" images. """ if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") l_data = self.data.sel(bands=['L...
python
def palettize(self, colormap): """Palettize the current image using `colormap`. .. note:: Works only on "L" or "LA" images. """ if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") l_data = self.data.sel(bands=['L...
Palettize the current image using `colormap`. .. note:: Works only on "L" or "LA" images.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L984-L1012
pytroll/trollimage
trollimage/xrimage.py
XRImage.blend
def blend(self, other): """Alpha blend *other* on top of the current image.""" raise NotImplementedError("This method has not be implemented for " "xarray support.") if self.mode != "RGBA" or other.mode != "RGBA": raise ValueError("Images must be in...
python
def blend(self, other): """Alpha blend *other* on top of the current image.""" raise NotImplementedError("This method has not be implemented for " "xarray support.") if self.mode != "RGBA" or other.mode != "RGBA": raise ValueError("Images must be in...
Alpha blend *other* on top of the current image.
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L1014-L1029
srstevenson/xdg
src/xdg.py
_path_from_env
def _path_from_env(variable: str, default: Path) -> Path: """Read an environment variable as a path. The environment variable with the specified name is read, and its value returned as a path. If the environment variable is not set, or set to the empty string, the default value is returned. Parame...
python
def _path_from_env(variable: str, default: Path) -> Path: """Read an environment variable as a path. The environment variable with the specified name is read, and its value returned as a path. If the environment variable is not set, or set to the empty string, the default value is returned. Parame...
Read an environment variable as a path. The environment variable with the specified name is read, and its value returned as a path. If the environment variable is not set, or set to the empty string, the default value is returned. Parameters ---------- variable : str Name of the enviro...
https://github.com/srstevenson/xdg/blob/ec570eee85d2750ac83e60eeb7e1ac592c8166a8/src/xdg.py#L51-L75
srstevenson/xdg
src/xdg.py
_paths_from_env
def _paths_from_env(variable: str, default: List[Path]) -> List[Path]: """Read an environment variable as a list of paths. The environment variable with the specified name is read, and its value split on colons and returned as a list of paths. If the environment variable is not set, or set to the empty...
python
def _paths_from_env(variable: str, default: List[Path]) -> List[Path]: """Read an environment variable as a list of paths. The environment variable with the specified name is read, and its value split on colons and returned as a list of paths. If the environment variable is not set, or set to the empty...
Read an environment variable as a list of paths. The environment variable with the specified name is read, and its value split on colons and returned as a list of paths. If the environment variable is not set, or set to the empty string, the default value is returned. Parameters ---------- ...
https://github.com/srstevenson/xdg/blob/ec570eee85d2750ac83e60eeb7e1ac592c8166a8/src/xdg.py#L78-L103
thesharp/htpasswd
htpasswd/basic.py
Basic.add
def add(self, user, password): """ Adds a user with password """ if self.__contains__(user): raise UserExists self.new_users[user] = self._encrypt_password(password) + "\n"
python
def add(self, user, password): """ Adds a user with password """ if self.__contains__(user): raise UserExists self.new_users[user] = self._encrypt_password(password) + "\n"
Adds a user with password
https://github.com/thesharp/htpasswd/blob/8bf5cee0bd5362af586729f4c9cea8131eedd74f/htpasswd/basic.py#L70-L74
thesharp/htpasswd
htpasswd/basic.py
Basic.pop
def pop(self, user): """ Deletes a user """ if not self.__contains__(user): raise UserNotExists self.new_users.pop(user)
python
def pop(self, user): """ Deletes a user """ if not self.__contains__(user): raise UserNotExists self.new_users.pop(user)
Deletes a user
https://github.com/thesharp/htpasswd/blob/8bf5cee0bd5362af586729f4c9cea8131eedd74f/htpasswd/basic.py#L76-L80
thesharp/htpasswd
htpasswd/basic.py
Basic.change_password
def change_password(self, user, password): """ Changes user password """ if not self.__contains__(user): raise UserNotExists self.new_users[user] = self._encrypt_password(password) + "\n"
python
def change_password(self, user, password): """ Changes user password """ if not self.__contains__(user): raise UserNotExists self.new_users[user] = self._encrypt_password(password) + "\n"
Changes user password
https://github.com/thesharp/htpasswd/blob/8bf5cee0bd5362af586729f4c9cea8131eedd74f/htpasswd/basic.py#L82-L86
thesharp/htpasswd
htpasswd/basic.py
Basic._encrypt_password
def _encrypt_password(self, password): """encrypt the password for given mode """ if self.encryption_mode.lower() == 'crypt': return self._crypt_password(password) elif self.encryption_mode.lower() == 'md5': return self._md5_password(password) elif self.encryption...
python
def _encrypt_password(self, password): """encrypt the password for given mode """ if self.encryption_mode.lower() == 'crypt': return self._crypt_password(password) elif self.encryption_mode.lower() == 'md5': return self._md5_password(password) elif self.encryption...
encrypt the password for given mode
https://github.com/thesharp/htpasswd/blob/8bf5cee0bd5362af586729f4c9cea8131eedd74f/htpasswd/basic.py#L88-L97
thesharp/htpasswd
htpasswd/basic.py
Basic._crypt_password
def _crypt_password(self, password): """ Crypts password """ def salt(): """ Generates some salt """ symbols = ascii_letters + digits return choice(symbols) + choice(symbols) return crypt(password, salt())
python
def _crypt_password(self, password): """ Crypts password """ def salt(): """ Generates some salt """ symbols = ascii_letters + digits return choice(symbols) + choice(symbols) return crypt(password, salt())
Crypts password
https://github.com/thesharp/htpasswd/blob/8bf5cee0bd5362af586729f4c9cea8131eedd74f/htpasswd/basic.py#L99-L107
thesharp/htpasswd
htpasswd/group.py
Group.add_user
def add_user(self, user, group): """ Adds user to a group """ if self.is_user_in(user, group): raise UserAlreadyInAGroup self.new_groups.add(group, user)
python
def add_user(self, user, group): """ Adds user to a group """ if self.is_user_in(user, group): raise UserAlreadyInAGroup self.new_groups.add(group, user)
Adds user to a group
https://github.com/thesharp/htpasswd/blob/8bf5cee0bd5362af586729f4c9cea8131eedd74f/htpasswd/group.py#L63-L67
thesharp/htpasswd
htpasswd/group.py
Group.delete_user
def delete_user(self, user, group): """ Deletes user from group """ if not self.__contains__(group): raise GroupNotExists if not self.is_user_in(user, group): raise UserNotInAGroup self.new_groups.popvalue(group, user)
python
def delete_user(self, user, group): """ Deletes user from group """ if not self.__contains__(group): raise GroupNotExists if not self.is_user_in(user, group): raise UserNotInAGroup self.new_groups.popvalue(group, user)
Deletes user from group
https://github.com/thesharp/htpasswd/blob/8bf5cee0bd5362af586729f4c9cea8131eedd74f/htpasswd/group.py#L69-L75
openstack/swauth
swauth/middleware.py
filter_factory
def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def auth_filter(app): return Swauth(app, conf) return auth_filter
python
def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def auth_filter(app): return Swauth(app, conf) return auth_filter
Returns a WSGI filter app for use with paste.deploy.
https://github.com/openstack/swauth/blob/0c8eaf50a9e2b3317f3eba62f205546904bc6d74/swauth/middleware.py#L1702-L1709
openstack/swauth
swauth/middleware.py
Swauth.make_pre_authed_request
def make_pre_authed_request(self, env, method=None, path=None, body=None, headers=None): """Nearly the same as swift.common.wsgi.make_pre_authed_request except that this also always sets the 'swift.source' and user agent. Newer Swift code will support swi...
python
def make_pre_authed_request(self, env, method=None, path=None, body=None, headers=None): """Nearly the same as swift.common.wsgi.make_pre_authed_request except that this also always sets the 'swift.source' and user agent. Newer Swift code will support swi...
Nearly the same as swift.common.wsgi.make_pre_authed_request except that this also always sets the 'swift.source' and user agent. Newer Swift code will support swift_source as a kwarg, but we do it this way so we don't have to have a newer Swift. Since we're doing this anyway, ...
https://github.com/openstack/swauth/blob/0c8eaf50a9e2b3317f3eba62f205546904bc6d74/swauth/middleware.py#L179-L201
openstack/swauth
swauth/middleware.py
Swauth._get_concealed_token
def _get_concealed_token(self, token): """Returns hashed token to be used as object name in Swift. Tokens are stored in auth account but object names are visible in Swift logs. Object names are hashed from token. """ enc_key = "%s:%s:%s" % (HASH_PATH_PREFIX, token, HASH_PATH_SUF...
python
def _get_concealed_token(self, token): """Returns hashed token to be used as object name in Swift. Tokens are stored in auth account but object names are visible in Swift logs. Object names are hashed from token. """ enc_key = "%s:%s:%s" % (HASH_PATH_PREFIX, token, HASH_PATH_SUF...
Returns hashed token to be used as object name in Swift. Tokens are stored in auth account but object names are visible in Swift logs. Object names are hashed from token.
https://github.com/openstack/swauth/blob/0c8eaf50a9e2b3317f3eba62f205546904bc6d74/swauth/middleware.py#L296-L303
openstack/swauth
swauth/middleware.py
Swauth.get_groups
def get_groups(self, env, token): """Get groups for the given token. :param env: The current WSGI environment dictionary. :param token: Token to validate and return a group string for. :returns: None if the token is invalid or a string containing a comma separated lis...
python
def get_groups(self, env, token): """Get groups for the given token. :param env: The current WSGI environment dictionary. :param token: Token to validate and return a group string for. :returns: None if the token is invalid or a string containing a comma separated lis...
Get groups for the given token. :param env: The current WSGI environment dictionary. :param token: Token to validate and return a group string for. :returns: None if the token is invalid or a string containing a comma separated list of groups the authenticated user is a membe...
https://github.com/openstack/swauth/blob/0c8eaf50a9e2b3317f3eba62f205546904bc6d74/swauth/middleware.py#L305-L436
openstack/swauth
swauth/middleware.py
Swauth.authorize
def authorize(self, req): """Returns None if the request is authorized to continue or a standard WSGI response callable if not. """ try: version, account, container, obj = split_path(req.path, 1, 4, True) except ValueError: return HTTPNotFound(request=req)...
python
def authorize(self, req): """Returns None if the request is authorized to continue or a standard WSGI response callable if not. """ try: version, account, container, obj = split_path(req.path, 1, 4, True) except ValueError: return HTTPNotFound(request=req)...
Returns None if the request is authorized to continue or a standard WSGI response callable if not.
https://github.com/openstack/swauth/blob/0c8eaf50a9e2b3317f3eba62f205546904bc6d74/swauth/middleware.py#L438-L477
openstack/swauth
swauth/middleware.py
Swauth.denied_response
def denied_response(self, req): """Returns a standard WSGI response callable with the status of 403 or 401 depending on whether the REMOTE_USER is set or not. """ if not hasattr(req, 'credentials_valid'): req.credentials_valid = None if req.remote_user or req.credenti...
python
def denied_response(self, req): """Returns a standard WSGI response callable with the status of 403 or 401 depending on whether the REMOTE_USER is set or not. """ if not hasattr(req, 'credentials_valid'): req.credentials_valid = None if req.remote_user or req.credenti...
Returns a standard WSGI response callable with the status of 403 or 401 depending on whether the REMOTE_USER is set or not.
https://github.com/openstack/swauth/blob/0c8eaf50a9e2b3317f3eba62f205546904bc6d74/swauth/middleware.py#L479-L488
openstack/swauth
swauth/middleware.py
Swauth.handle
def handle(self, env, start_response): """WSGI entry point for auth requests (ones that match the self.auth_prefix). Wraps env in swob.Request object and passes it down. :param env: WSGI environment dictionary :param start_response: WSGI callable """ try: ...
python
def handle(self, env, start_response): """WSGI entry point for auth requests (ones that match the self.auth_prefix). Wraps env in swob.Request object and passes it down. :param env: WSGI environment dictionary :param start_response: WSGI callable """ try: ...
WSGI entry point for auth requests (ones that match the self.auth_prefix). Wraps env in swob.Request object and passes it down. :param env: WSGI environment dictionary :param start_response: WSGI callable
https://github.com/openstack/swauth/blob/0c8eaf50a9e2b3317f3eba62f205546904bc6d74/swauth/middleware.py#L490-L523
openstack/swauth
swauth/middleware.py
Swauth.handle_request
def handle_request(self, req): """Entry point for auth requests (ones that match the self.auth_prefix). Should return a WSGI-style callable (such as swob.Response). :param req: swob.Request object """ req.start_time = time() handler = None try: versio...
python
def handle_request(self, req): """Entry point for auth requests (ones that match the self.auth_prefix). Should return a WSGI-style callable (such as swob.Response). :param req: swob.Request object """ req.start_time = time() handler = None try: versio...
Entry point for auth requests (ones that match the self.auth_prefix). Should return a WSGI-style callable (such as swob.Response). :param req: swob.Request object
https://github.com/openstack/swauth/blob/0c8eaf50a9e2b3317f3eba62f205546904bc6d74/swauth/middleware.py#L525-L577