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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
8,700
SmileyChris/easy-thumbnails
easy_thumbnails/templatetags/thumbnail.py
data_uri
def data_uri(thumbnail): """ This filter will return the base64 encoded data URI for a given thumbnail object. Example usage:: {% thumbnail sample_image 25x25 crop as thumb %} <img src="{{ thumb|data_uri }}"> will for instance be rendered as: <img src="data:image/png;base64,i...
python
def data_uri(thumbnail): """ This filter will return the base64 encoded data URI for a given thumbnail object. Example usage:: {% thumbnail sample_image 25x25 crop as thumb %} <img src="{{ thumb|data_uri }}"> will for instance be rendered as: <img src="data:image/png;base64,i...
[ "def", "data_uri", "(", "thumbnail", ")", ":", "try", ":", "thumbnail", ".", "open", "(", "'rb'", ")", "data", "=", "thumbnail", ".", "read", "(", ")", "finally", ":", "thumbnail", ".", "close", "(", ")", "mime_type", "=", "mimetypes", ".", "guess_type...
This filter will return the base64 encoded data URI for a given thumbnail object. Example usage:: {% thumbnail sample_image 25x25 crop as thumb %} <img src="{{ thumb|data_uri }}"> will for instance be rendered as: <img src="data:image/png;base64,iVBORw0KGgo...">
[ "This", "filter", "will", "return", "the", "base64", "encoded", "data", "URI", "for", "a", "given", "thumbnail", "object", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/templatetags/thumbnail.py#L306-L326
8,701
SmileyChris/easy-thumbnails
setup.py
read_files
def read_files(*filenames): """ Output the contents of one or more files to a single concatenated string. """ output = [] for filename in filenames: f = codecs.open(filename, encoding='utf-8') try: output.append(f.read()) finally: f.close() return ...
python
def read_files(*filenames): """ Output the contents of one or more files to a single concatenated string. """ output = [] for filename in filenames: f = codecs.open(filename, encoding='utf-8') try: output.append(f.read()) finally: f.close() return ...
[ "def", "read_files", "(", "*", "filenames", ")", ":", "output", "=", "[", "]", "for", "filename", "in", "filenames", ":", "f", "=", "codecs", ".", "open", "(", "filename", ",", "encoding", "=", "'utf-8'", ")", "try", ":", "output", ".", "append", "("...
Output the contents of one or more files to a single concatenated string.
[ "Output", "the", "contents", "of", "one", "or", "more", "files", "to", "a", "single", "concatenated", "string", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/setup.py#L26-L37
8,702
SmileyChris/easy-thumbnails
easy_thumbnails/management/__init__.py
all_thumbnails
def all_thumbnails(path, recursive=True, prefix=None, subdir=None): """ Return a dictionary referencing all files which match the thumbnail format. Each key is a source image filename, relative to path. Each value is a list of dictionaries as explained in `thumbnails_for_file`. """ if prefix is...
python
def all_thumbnails(path, recursive=True, prefix=None, subdir=None): """ Return a dictionary referencing all files which match the thumbnail format. Each key is a source image filename, relative to path. Each value is a list of dictionaries as explained in `thumbnails_for_file`. """ if prefix is...
[ "def", "all_thumbnails", "(", "path", ",", "recursive", "=", "True", ",", "prefix", "=", "None", ",", "subdir", "=", "None", ")", ":", "if", "prefix", "is", "None", ":", "prefix", "=", "settings", ".", "THUMBNAIL_PREFIX", "if", "subdir", "is", "None", ...
Return a dictionary referencing all files which match the thumbnail format. Each key is a source image filename, relative to path. Each value is a list of dictionaries as explained in `thumbnails_for_file`.
[ "Return", "a", "dictionary", "referencing", "all", "files", "which", "match", "the", "thumbnail", "format", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/__init__.py#L11-L61
8,703
SmileyChris/easy-thumbnails
easy_thumbnails/management/__init__.py
thumbnails_for_file
def thumbnails_for_file(relative_source_path, root=None, basedir=None, subdir=None, prefix=None): """ Return a list of dictionaries, one for each thumbnail belonging to the source image. The following list explains each key of the dictionary: `filename` -- absolute thumb...
python
def thumbnails_for_file(relative_source_path, root=None, basedir=None, subdir=None, prefix=None): """ Return a list of dictionaries, one for each thumbnail belonging to the source image. The following list explains each key of the dictionary: `filename` -- absolute thumb...
[ "def", "thumbnails_for_file", "(", "relative_source_path", ",", "root", "=", "None", ",", "basedir", "=", "None", ",", "subdir", "=", "None", ",", "prefix", "=", "None", ")", ":", "if", "root", "is", "None", ":", "root", "=", "settings", ".", "MEDIA_ROOT...
Return a list of dictionaries, one for each thumbnail belonging to the source image. The following list explains each key of the dictionary: `filename` -- absolute thumbnail path `x` and `y` -- the size of the thumbnail `options` -- list of options for this thumbnail `quality` -- ...
[ "Return", "a", "list", "of", "dictionaries", "one", "for", "each", "thumbnail", "belonging", "to", "the", "source", "image", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/__init__.py#L64-L91
8,704
SmileyChris/easy-thumbnails
easy_thumbnails/management/__init__.py
delete_thumbnails
def delete_thumbnails(relative_source_path, root=None, basedir=None, subdir=None, prefix=None): """ Delete all thumbnails for a source image. """ thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir, prefix) return _delete_us...
python
def delete_thumbnails(relative_source_path, root=None, basedir=None, subdir=None, prefix=None): """ Delete all thumbnails for a source image. """ thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir, prefix) return _delete_us...
[ "def", "delete_thumbnails", "(", "relative_source_path", ",", "root", "=", "None", ",", "basedir", "=", "None", ",", "subdir", "=", "None", ",", "prefix", "=", "None", ")", ":", "thumbs", "=", "thumbnails_for_file", "(", "relative_source_path", ",", "root", ...
Delete all thumbnails for a source image.
[ "Delete", "all", "thumbnails", "for", "a", "source", "image", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/__init__.py#L94-L101
8,705
SmileyChris/easy-thumbnails
easy_thumbnails/management/__init__.py
delete_all_thumbnails
def delete_all_thumbnails(path, recursive=True): """ Delete all files within a path which match the thumbnails pattern. By default, matching files from all sub-directories are also removed. To only remove from the path directory, set recursive=False. """ total = 0 for thumbs in all_thumbnai...
python
def delete_all_thumbnails(path, recursive=True): """ Delete all files within a path which match the thumbnails pattern. By default, matching files from all sub-directories are also removed. To only remove from the path directory, set recursive=False. """ total = 0 for thumbs in all_thumbnai...
[ "def", "delete_all_thumbnails", "(", "path", ",", "recursive", "=", "True", ")", ":", "total", "=", "0", "for", "thumbs", "in", "all_thumbnails", "(", "path", ",", "recursive", "=", "recursive", ")", ".", "values", "(", ")", ":", "total", "+=", "_delete_...
Delete all files within a path which match the thumbnails pattern. By default, matching files from all sub-directories are also removed. To only remove from the path directory, set recursive=False.
[ "Delete", "all", "files", "within", "a", "path", "which", "match", "the", "thumbnails", "pattern", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/__init__.py#L117-L127
8,706
SmileyChris/easy-thumbnails
easy_thumbnails/signal_handlers.py
signal_committed_filefields
def signal_committed_filefields(sender, instance, **kwargs): """ A post_save signal handler which sends a signal for each ``FileField`` that was committed this save. """ for field_name in getattr(instance, '_uncommitted_filefields', ()): fieldfile = getattr(instance, field_name) # Do...
python
def signal_committed_filefields(sender, instance, **kwargs): """ A post_save signal handler which sends a signal for each ``FileField`` that was committed this save. """ for field_name in getattr(instance, '_uncommitted_filefields', ()): fieldfile = getattr(instance, field_name) # Do...
[ "def", "signal_committed_filefields", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "for", "field_name", "in", "getattr", "(", "instance", ",", "'_uncommitted_filefields'", ",", "(", ")", ")", ":", "fieldfile", "=", "getattr", "(", "inst...
A post_save signal handler which sends a signal for each ``FileField`` that was committed this save.
[ "A", "post_save", "signal", "handler", "which", "sends", "a", "signal", "for", "each", "FileField", "that", "was", "committed", "this", "save", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/signal_handlers.py#L25-L34
8,707
SmileyChris/easy-thumbnails
easy_thumbnails/signal_handlers.py
generate_aliases
def generate_aliases(fieldfile, **kwargs): """ A saved_file signal handler which generates thumbnails for all field, model, and app specific aliases matching the saved file's field. """ # Avoids circular import. from easy_thumbnails.files import generate_all_aliases generate_all_aliases(fiel...
python
def generate_aliases(fieldfile, **kwargs): """ A saved_file signal handler which generates thumbnails for all field, model, and app specific aliases matching the saved file's field. """ # Avoids circular import. from easy_thumbnails.files import generate_all_aliases generate_all_aliases(fiel...
[ "def", "generate_aliases", "(", "fieldfile", ",", "*", "*", "kwargs", ")", ":", "# Avoids circular import.", "from", "easy_thumbnails", ".", "files", "import", "generate_all_aliases", "generate_all_aliases", "(", "fieldfile", ",", "include_global", "=", "False", ")" ]
A saved_file signal handler which generates thumbnails for all field, model, and app specific aliases matching the saved file's field.
[ "A", "saved_file", "signal", "handler", "which", "generates", "thumbnails", "for", "all", "field", "model", "and", "app", "specific", "aliases", "matching", "the", "saved", "file", "s", "field", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/signal_handlers.py#L37-L44
8,708
SmileyChris/easy-thumbnails
easy_thumbnails/signal_handlers.py
generate_aliases_global
def generate_aliases_global(fieldfile, **kwargs): """ A saved_file signal handler which generates thumbnails for all field, model, and app specific aliases matching the saved file's field, also generating thumbnails for each project-wide alias. """ # Avoids circular import. from easy_thumbna...
python
def generate_aliases_global(fieldfile, **kwargs): """ A saved_file signal handler which generates thumbnails for all field, model, and app specific aliases matching the saved file's field, also generating thumbnails for each project-wide alias. """ # Avoids circular import. from easy_thumbna...
[ "def", "generate_aliases_global", "(", "fieldfile", ",", "*", "*", "kwargs", ")", ":", "# Avoids circular import.", "from", "easy_thumbnails", ".", "files", "import", "generate_all_aliases", "generate_all_aliases", "(", "fieldfile", ",", "include_global", "=", "True", ...
A saved_file signal handler which generates thumbnails for all field, model, and app specific aliases matching the saved file's field, also generating thumbnails for each project-wide alias.
[ "A", "saved_file", "signal", "handler", "which", "generates", "thumbnails", "for", "all", "field", "model", "and", "app", "specific", "aliases", "matching", "the", "saved", "file", "s", "field", "also", "generating", "thumbnails", "for", "each", "project", "-", ...
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/signal_handlers.py#L47-L55
8,709
SmileyChris/easy-thumbnails
easy_thumbnails/processors.py
colorspace
def colorspace(im, bw=False, replace_alpha=False, **kwargs): """ Convert images to the correct color space. A passive option (i.e. always processed) of this method is that all images (unless grayscale) are converted to RGB colorspace. This processor should be listed before :func:`scale_and_crop` s...
python
def colorspace(im, bw=False, replace_alpha=False, **kwargs): """ Convert images to the correct color space. A passive option (i.e. always processed) of this method is that all images (unless grayscale) are converted to RGB colorspace. This processor should be listed before :func:`scale_and_crop` s...
[ "def", "colorspace", "(", "im", ",", "bw", "=", "False", ",", "replace_alpha", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "im", ".", "mode", "==", "'I'", ":", "# PIL (and pillow) have can't convert 16 bit grayscale images to lower", "# modes, so manual...
Convert images to the correct color space. A passive option (i.e. always processed) of this method is that all images (unless grayscale) are converted to RGB colorspace. This processor should be listed before :func:`scale_and_crop` so palette is changed before the image is resized. bw Mak...
[ "Convert", "images", "to", "the", "correct", "color", "space", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/processors.py#L45-L90
8,710
SmileyChris/easy-thumbnails
easy_thumbnails/processors.py
autocrop
def autocrop(im, autocrop=False, **kwargs): """ Remove any unnecessary whitespace from the edges of the source image. This processor should be listed before :func:`scale_and_crop` so the whitespace is removed from the source image before it is resized. autocrop Activates the autocrop metho...
python
def autocrop(im, autocrop=False, **kwargs): """ Remove any unnecessary whitespace from the edges of the source image. This processor should be listed before :func:`scale_and_crop` so the whitespace is removed from the source image before it is resized. autocrop Activates the autocrop metho...
[ "def", "autocrop", "(", "im", ",", "autocrop", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "autocrop", ":", "# If transparent, flatten.", "if", "utils", ".", "is_transparent", "(", "im", ")", ":", "no_alpha", "=", "Image", ".", "new", "(", "...
Remove any unnecessary whitespace from the edges of the source image. This processor should be listed before :func:`scale_and_crop` so the whitespace is removed from the source image before it is resized. autocrop Activates the autocrop method for this image.
[ "Remove", "any", "unnecessary", "whitespace", "from", "the", "edges", "of", "the", "source", "image", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/processors.py#L93-L119
8,711
SmileyChris/easy-thumbnails
easy_thumbnails/processors.py
filters
def filters(im, detail=False, sharpen=False, **kwargs): """ Pass the source image through post-processing filters. sharpen Sharpen the thumbnail image (using the PIL sharpen filter) detail Add detail to the image, like a mild *sharpen* (using the PIL ``detail`` filter). ""...
python
def filters(im, detail=False, sharpen=False, **kwargs): """ Pass the source image through post-processing filters. sharpen Sharpen the thumbnail image (using the PIL sharpen filter) detail Add detail to the image, like a mild *sharpen* (using the PIL ``detail`` filter). ""...
[ "def", "filters", "(", "im", ",", "detail", "=", "False", ",", "sharpen", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "detail", ":", "im", "=", "im", ".", "filter", "(", "ImageFilter", ".", "DETAIL", ")", "if", "sharpen", ":", "im", "=...
Pass the source image through post-processing filters. sharpen Sharpen the thumbnail image (using the PIL sharpen filter) detail Add detail to the image, like a mild *sharpen* (using the PIL ``detail`` filter).
[ "Pass", "the", "source", "image", "through", "post", "-", "processing", "filters", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/processors.py#L280-L296
8,712
SmileyChris/easy-thumbnails
easy_thumbnails/processors.py
background
def background(im, size, background=None, **kwargs): """ Add borders of a certain color to make the resized image fit exactly within the dimensions given. background Background color to use """ if not background: # Primary option not given, nothing to do. return im i...
python
def background(im, size, background=None, **kwargs): """ Add borders of a certain color to make the resized image fit exactly within the dimensions given. background Background color to use """ if not background: # Primary option not given, nothing to do. return im i...
[ "def", "background", "(", "im", ",", "size", ",", "background", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "background", ":", "# Primary option not given, nothing to do.", "return", "im", "if", "not", "size", "[", "0", "]", "or", "not", ...
Add borders of a certain color to make the resized image fit exactly within the dimensions given. background Background color to use
[ "Add", "borders", "of", "a", "certain", "color", "to", "make", "the", "resized", "image", "fit", "exactly", "within", "the", "dimensions", "given", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/processors.py#L299-L324
8,713
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
generate_all_aliases
def generate_all_aliases(fieldfile, include_global): """ Generate all of a file's aliases. :param fieldfile: A ``FieldFile`` instance. :param include_global: A boolean which determines whether to generate thumbnails for project-wide aliases in addition to field, model, and app specific ...
python
def generate_all_aliases(fieldfile, include_global): """ Generate all of a file's aliases. :param fieldfile: A ``FieldFile`` instance. :param include_global: A boolean which determines whether to generate thumbnails for project-wide aliases in addition to field, model, and app specific ...
[ "def", "generate_all_aliases", "(", "fieldfile", ",", "include_global", ")", ":", "all_options", "=", "aliases", ".", "all", "(", "fieldfile", ",", "include_global", "=", "include_global", ")", "if", "all_options", ":", "thumbnailer", "=", "get_thumbnailer", "(", ...
Generate all of a file's aliases. :param fieldfile: A ``FieldFile`` instance. :param include_global: A boolean which determines whether to generate thumbnails for project-wide aliases in addition to field, model, and app specific aliases.
[ "Generate", "all", "of", "a", "file", "s", "aliases", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L79-L93
8,714
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
ThumbnailFile._get_image
def _get_image(self): """ Get a PIL Image instance of this file. The image is cached to avoid the file needing to be read again if the function is called again. """ if not hasattr(self, '_image_cache'): from easy_thumbnails.source_generators import pil_image ...
python
def _get_image(self): """ Get a PIL Image instance of this file. The image is cached to avoid the file needing to be read again if the function is called again. """ if not hasattr(self, '_image_cache'): from easy_thumbnails.source_generators import pil_image ...
[ "def", "_get_image", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_image_cache'", ")", ":", "from", "easy_thumbnails", ".", "source_generators", "import", "pil_image", "self", ".", "image", "=", "pil_image", "(", "self", ")", "return", ...
Get a PIL Image instance of this file. The image is cached to avoid the file needing to be read again if the function is called again.
[ "Get", "a", "PIL", "Image", "instance", "of", "this", "file", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L183-L193
8,715
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
ThumbnailFile._set_image
def _set_image(self, image): """ Set the image for this file. This also caches the dimensions of the image. """ if image: self._image_cache = image self._dimensions_cache = image.size else: if hasattr(self, '_image_cache'): ...
python
def _set_image(self, image): """ Set the image for this file. This also caches the dimensions of the image. """ if image: self._image_cache = image self._dimensions_cache = image.size else: if hasattr(self, '_image_cache'): ...
[ "def", "_set_image", "(", "self", ",", "image", ")", ":", "if", "image", ":", "self", ".", "_image_cache", "=", "image", "self", ".", "_dimensions_cache", "=", "image", ".", "size", "else", ":", "if", "hasattr", "(", "self", ",", "'_image_cache'", ")", ...
Set the image for this file. This also caches the dimensions of the image.
[ "Set", "the", "image", "for", "this", "file", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L195-L208
8,716
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
ThumbnailFile.set_image_dimensions
def set_image_dimensions(self, thumbnail): """ Set image dimensions from the cached dimensions of a ``Thumbnail`` model instance. """ try: dimensions = getattr(thumbnail, 'dimensions', None) except models.ThumbnailDimensions.DoesNotExist: dimension...
python
def set_image_dimensions(self, thumbnail): """ Set image dimensions from the cached dimensions of a ``Thumbnail`` model instance. """ try: dimensions = getattr(thumbnail, 'dimensions', None) except models.ThumbnailDimensions.DoesNotExist: dimension...
[ "def", "set_image_dimensions", "(", "self", ",", "thumbnail", ")", ":", "try", ":", "dimensions", "=", "getattr", "(", "thumbnail", ",", "'dimensions'", ",", "None", ")", "except", "models", ".", "ThumbnailDimensions", ".", "DoesNotExist", ":", "dimensions", "...
Set image dimensions from the cached dimensions of a ``Thumbnail`` model instance.
[ "Set", "image", "dimensions", "from", "the", "cached", "dimensions", "of", "a", "Thumbnail", "model", "instance", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L274-L286
8,717
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
Thumbnailer.generate_thumbnail
def generate_thumbnail(self, thumbnail_options, high_resolution=False, silent_template_exception=False): """ Return an unsaved ``ThumbnailFile`` containing a thumbnail image. The thumbnail image is generated using the ``thumbnail_options`` dictionary. ...
python
def generate_thumbnail(self, thumbnail_options, high_resolution=False, silent_template_exception=False): """ Return an unsaved ``ThumbnailFile`` containing a thumbnail image. The thumbnail image is generated using the ``thumbnail_options`` dictionary. ...
[ "def", "generate_thumbnail", "(", "self", ",", "thumbnail_options", ",", "high_resolution", "=", "False", ",", "silent_template_exception", "=", "False", ")", ":", "thumbnail_options", "=", "self", ".", "get_options", "(", "thumbnail_options", ")", "orig_size", "=",...
Return an unsaved ``ThumbnailFile`` containing a thumbnail image. The thumbnail image is generated using the ``thumbnail_options`` dictionary.
[ "Return", "an", "unsaved", "ThumbnailFile", "containing", "a", "thumbnail", "image", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L359-L413
8,718
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
Thumbnailer.get_existing_thumbnail
def get_existing_thumbnail(self, thumbnail_options, high_resolution=False): """ Return a ``ThumbnailFile`` containing an existing thumbnail for a set of thumbnail options, or ``None`` if not found. """ thumbnail_options = self.get_options(thumbnail_options) names = [ ...
python
def get_existing_thumbnail(self, thumbnail_options, high_resolution=False): """ Return a ``ThumbnailFile`` containing an existing thumbnail for a set of thumbnail options, or ``None`` if not found. """ thumbnail_options = self.get_options(thumbnail_options) names = [ ...
[ "def", "get_existing_thumbnail", "(", "self", ",", "thumbnail_options", ",", "high_resolution", "=", "False", ")", ":", "thumbnail_options", "=", "self", ".", "get_options", "(", "thumbnail_options", ")", "names", "=", "[", "self", ".", "get_thumbnail_name", "(", ...
Return a ``ThumbnailFile`` containing an existing thumbnail for a set of thumbnail options, or ``None`` if not found.
[ "Return", "a", "ThumbnailFile", "containing", "an", "existing", "thumbnail", "for", "a", "set", "of", "thumbnail", "options", "or", "None", "if", "not", "found", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L461-L488
8,719
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
Thumbnailer.get_thumbnail
def get_thumbnail(self, thumbnail_options, save=True, generate=None, silent_template_exception=False): """ Return a ``ThumbnailFile`` containing a thumbnail. If a matching thumbnail already exists, it will simply be returned. By default (unless the ``Thumbnailer``...
python
def get_thumbnail(self, thumbnail_options, save=True, generate=None, silent_template_exception=False): """ Return a ``ThumbnailFile`` containing a thumbnail. If a matching thumbnail already exists, it will simply be returned. By default (unless the ``Thumbnailer``...
[ "def", "get_thumbnail", "(", "self", ",", "thumbnail_options", ",", "save", "=", "True", ",", "generate", "=", "None", ",", "silent_template_exception", "=", "False", ")", ":", "thumbnail_options", "=", "self", ".", "get_options", "(", "thumbnail_options", ")", ...
Return a ``ThumbnailFile`` containing a thumbnail. If a matching thumbnail already exists, it will simply be returned. By default (unless the ``Thumbnailer`` was instanciated with ``generate=False``), thumbnails that don't exist are generated. Otherwise ``None`` is returned. F...
[ "Return", "a", "ThumbnailFile", "containing", "a", "thumbnail", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L490-L544
8,720
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
Thumbnailer.save_thumbnail
def save_thumbnail(self, thumbnail): """ Save a thumbnail to the thumbnail_storage. Also triggers the ``thumbnail_created`` signal and caches the thumbnail values and dimensions for future lookups. """ filename = thumbnail.name try: self.thumbnail_sto...
python
def save_thumbnail(self, thumbnail): """ Save a thumbnail to the thumbnail_storage. Also triggers the ``thumbnail_created`` signal and caches the thumbnail values and dimensions for future lookups. """ filename = thumbnail.name try: self.thumbnail_sto...
[ "def", "save_thumbnail", "(", "self", ",", "thumbnail", ")", ":", "filename", "=", "thumbnail", ".", "name", "try", ":", "self", ".", "thumbnail_storage", ".", "delete", "(", "filename", ")", "except", "Exception", ":", "pass", "self", ".", "thumbnail_storag...
Save a thumbnail to the thumbnail_storage. Also triggers the ``thumbnail_created`` signal and caches the thumbnail values and dimensions for future lookups.
[ "Save", "a", "thumbnail", "to", "the", "thumbnail_storage", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L546-L575
8,721
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
Thumbnailer.thumbnail_exists
def thumbnail_exists(self, thumbnail_name): """ Calculate whether the thumbnail already exists and that the source is not newer than the thumbnail. If the source and thumbnail file storages are local, their file modification times are used. Otherwise the database cached modifica...
python
def thumbnail_exists(self, thumbnail_name): """ Calculate whether the thumbnail already exists and that the source is not newer than the thumbnail. If the source and thumbnail file storages are local, their file modification times are used. Otherwise the database cached modifica...
[ "def", "thumbnail_exists", "(", "self", ",", "thumbnail_name", ")", ":", "if", "self", ".", "remote_source", ":", "return", "False", "if", "utils", ".", "is_storage_local", "(", "self", ".", "source_storage", ")", ":", "source_modtime", "=", "utils", ".", "g...
Calculate whether the thumbnail already exists and that the source is not newer than the thumbnail. If the source and thumbnail file storages are local, their file modification times are used. Otherwise the database cached modification times are used.
[ "Calculate", "whether", "the", "thumbnail", "already", "exists", "and", "that", "the", "source", "is", "not", "newer", "than", "the", "thumbnail", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L577-L616
8,722
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
ThumbnailerFieldFile.save
def save(self, name, content, *args, **kwargs): """ Save the file, also saving a reference to the thumbnail cache Source model. """ super(ThumbnailerFieldFile, self).save(name, content, *args, **kwargs) self.get_source_cache(create=True, update=True)
python
def save(self, name, content, *args, **kwargs): """ Save the file, also saving a reference to the thumbnail cache Source model. """ super(ThumbnailerFieldFile, self).save(name, content, *args, **kwargs) self.get_source_cache(create=True, update=True)
[ "def", "save", "(", "self", ",", "name", ",", "content", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "ThumbnailerFieldFile", ",", "self", ")", ".", "save", "(", "name", ",", "content", ",", "*", "args", ",", "*", "*", "kwar...
Save the file, also saving a reference to the thumbnail cache Source model.
[ "Save", "the", "file", "also", "saving", "a", "reference", "to", "the", "thumbnail", "cache", "Source", "model", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L665-L671
8,723
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
ThumbnailerFieldFile.delete
def delete(self, *args, **kwargs): """ Delete the image, along with any generated thumbnails. """ source_cache = self.get_source_cache() # First, delete any related thumbnails. self.delete_thumbnails(source_cache) # Next, delete the source image. super(Thu...
python
def delete(self, *args, **kwargs): """ Delete the image, along with any generated thumbnails. """ source_cache = self.get_source_cache() # First, delete any related thumbnails. self.delete_thumbnails(source_cache) # Next, delete the source image. super(Thu...
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "source_cache", "=", "self", ".", "get_source_cache", "(", ")", "# First, delete any related thumbnails.", "self", ".", "delete_thumbnails", "(", "source_cache", ")", "# Next, del...
Delete the image, along with any generated thumbnails.
[ "Delete", "the", "image", "along", "with", "any", "generated", "thumbnails", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L673-L684
8,724
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
ThumbnailerFieldFile.delete_thumbnails
def delete_thumbnails(self, source_cache=None): """ Delete any thumbnails generated from the source image. :arg source_cache: An optional argument only used for optimisation where the source cache instance is already known. :returns: The number of files deleted. """ ...
python
def delete_thumbnails(self, source_cache=None): """ Delete any thumbnails generated from the source image. :arg source_cache: An optional argument only used for optimisation where the source cache instance is already known. :returns: The number of files deleted. """ ...
[ "def", "delete_thumbnails", "(", "self", ",", "source_cache", "=", "None", ")", ":", "source_cache", "=", "self", ".", "get_source_cache", "(", ")", "deleted", "=", "0", "if", "source_cache", ":", "thumbnail_storage_hash", "=", "utils", ".", "get_storage_hash", ...
Delete any thumbnails generated from the source image. :arg source_cache: An optional argument only used for optimisation where the source cache instance is already known. :returns: The number of files deleted.
[ "Delete", "any", "thumbnails", "generated", "from", "the", "source", "image", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L688-L709
8,725
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
ThumbnailerFieldFile.get_thumbnails
def get_thumbnails(self, *args, **kwargs): """ Return an iterator which returns ThumbnailFile instances. """ # First, delete any related thumbnails. source_cache = self.get_source_cache() if source_cache: thumbnail_storage_hash = utils.get_storage_hash( ...
python
def get_thumbnails(self, *args, **kwargs): """ Return an iterator which returns ThumbnailFile instances. """ # First, delete any related thumbnails. source_cache = self.get_source_cache() if source_cache: thumbnail_storage_hash = utils.get_storage_hash( ...
[ "def", "get_thumbnails", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# First, delete any related thumbnails.", "source_cache", "=", "self", ".", "get_source_cache", "(", ")", "if", "source_cache", ":", "thumbnail_storage_hash", "=", "utils",...
Return an iterator which returns ThumbnailFile instances.
[ "Return", "an", "iterator", "which", "returns", "ThumbnailFile", "instances", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L713-L727
8,726
SmileyChris/easy-thumbnails
easy_thumbnails/files.py
ThumbnailerImageFieldFile.save
def save(self, name, content, *args, **kwargs): """ Save the image. The image will be resized down using a ``ThumbnailField`` if ``resize_source`` (a dictionary of thumbnail options) is provided by the field. """ options = getattr(self.field, 'resize_source', Non...
python
def save(self, name, content, *args, **kwargs): """ Save the image. The image will be resized down using a ``ThumbnailField`` if ``resize_source`` (a dictionary of thumbnail options) is provided by the field. """ options = getattr(self.field, 'resize_source', Non...
[ "def", "save", "(", "self", ",", "name", ",", "content", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "options", "=", "getattr", "(", "self", ".", "field", ",", "'resize_source'", ",", "None", ")", "if", "options", ":", "if", "'quality'", "...
Save the image. The image will be resized down using a ``ThumbnailField`` if ``resize_source`` (a dictionary of thumbnail options) is provided by the field.
[ "Save", "the", "image", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L749-L769
8,727
SmileyChris/easy-thumbnails
easy_thumbnails/management/commands/thumbnail_cleanup.py
queryset_iterator
def queryset_iterator(queryset, chunksize=1000): """ The queryset iterator helps to keep the memory consumption down. And also making it easier to process for weaker computers. """ if queryset.exists(): primary_key = 0 last_pk = queryset.order_by('-pk')[0].pk queryset = query...
python
def queryset_iterator(queryset, chunksize=1000): """ The queryset iterator helps to keep the memory consumption down. And also making it easier to process for weaker computers. """ if queryset.exists(): primary_key = 0 last_pk = queryset.order_by('-pk')[0].pk queryset = query...
[ "def", "queryset_iterator", "(", "queryset", ",", "chunksize", "=", "1000", ")", ":", "if", "queryset", ".", "exists", "(", ")", ":", "primary_key", "=", "0", "last_pk", "=", "queryset", ".", "order_by", "(", "'-pk'", ")", "[", "0", "]", ".", "pk", "...
The queryset iterator helps to keep the memory consumption down. And also making it easier to process for weaker computers.
[ "The", "queryset", "iterator", "helps", "to", "keep", "the", "memory", "consumption", "down", ".", "And", "also", "making", "it", "easier", "to", "process", "for", "weaker", "computers", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/commands/thumbnail_cleanup.py#L105-L118
8,728
SmileyChris/easy-thumbnails
easy_thumbnails/management/commands/thumbnail_cleanup.py
ThumbnailCollectionCleaner.print_stats
def print_stats(self): """ Print statistics about the cleanup performed. """ print( "{0:-<48}".format(str(datetime.now().strftime('%Y-%m-%d %H:%M ')))) print("{0:<40} {1:>7}".format("Sources checked:", self.sources)) print("{0:<40} {1:>7}".format( ...
python
def print_stats(self): """ Print statistics about the cleanup performed. """ print( "{0:-<48}".format(str(datetime.now().strftime('%Y-%m-%d %H:%M ')))) print("{0:<40} {1:>7}".format("Sources checked:", self.sources)) print("{0:<40} {1:>7}".format( ...
[ "def", "print_stats", "(", "self", ")", ":", "print", "(", "\"{0:-<48}\"", ".", "format", "(", "str", "(", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M '", ")", ")", ")", ")", "print", "(", "\"{0:<40} {1:>7}\"", ".", "format",...
Print statistics about the cleanup performed.
[ "Print", "statistics", "about", "the", "cleanup", "performed", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/commands/thumbnail_cleanup.py#L91-L102
8,729
SmileyChris/easy-thumbnails
easy_thumbnails/alias.py
Aliases.populate_from_settings
def populate_from_settings(self): """ Populate the aliases from the ``THUMBNAIL_ALIASES`` setting. """ settings_aliases = settings.THUMBNAIL_ALIASES if settings_aliases: for target, aliases in settings_aliases.items(): target_aliases = self._aliases.se...
python
def populate_from_settings(self): """ Populate the aliases from the ``THUMBNAIL_ALIASES`` setting. """ settings_aliases = settings.THUMBNAIL_ALIASES if settings_aliases: for target, aliases in settings_aliases.items(): target_aliases = self._aliases.se...
[ "def", "populate_from_settings", "(", "self", ")", ":", "settings_aliases", "=", "settings", ".", "THUMBNAIL_ALIASES", "if", "settings_aliases", ":", "for", "target", ",", "aliases", "in", "settings_aliases", ".", "items", "(", ")", ":", "target_aliases", "=", "...
Populate the aliases from the ``THUMBNAIL_ALIASES`` setting.
[ "Populate", "the", "aliases", "from", "the", "THUMBNAIL_ALIASES", "setting", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L23-L31
8,730
SmileyChris/easy-thumbnails
easy_thumbnails/alias.py
Aliases.set
def set(self, alias, options, target=None): """ Add an alias. :param alias: The name of the alias to add. :param options: The easy-thumbnails options dictonary for this alias (should include ``size``). :param target: A field, model, or app to limit this alias to ...
python
def set(self, alias, options, target=None): """ Add an alias. :param alias: The name of the alias to add. :param options: The easy-thumbnails options dictonary for this alias (should include ``size``). :param target: A field, model, or app to limit this alias to ...
[ "def", "set", "(", "self", ",", "alias", ",", "options", ",", "target", "=", "None", ")", ":", "target", "=", "self", ".", "_coerce_target", "(", "target", ")", "or", "''", "target_aliases", "=", "self", ".", "_aliases", ".", "setdefault", "(", "target...
Add an alias. :param alias: The name of the alias to add. :param options: The easy-thumbnails options dictonary for this alias (should include ``size``). :param target: A field, model, or app to limit this alias to (optional).
[ "Add", "an", "alias", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L33-L45
8,731
SmileyChris/easy-thumbnails
easy_thumbnails/alias.py
Aliases.get
def get(self, alias, target=None): """ Get a dictionary of aliased options. :param alias: The name of the aliased options. :param target: Get alias for this specific target (optional). If no matching alias is found, returns ``None``. """ for target_part in rever...
python
def get(self, alias, target=None): """ Get a dictionary of aliased options. :param alias: The name of the aliased options. :param target: Get alias for this specific target (optional). If no matching alias is found, returns ``None``. """ for target_part in rever...
[ "def", "get", "(", "self", ",", "alias", ",", "target", "=", "None", ")", ":", "for", "target_part", "in", "reversed", "(", "list", "(", "self", ".", "_get_targets", "(", "target", ")", ")", ")", ":", "options", "=", "self", ".", "_get", "(", "targ...
Get a dictionary of aliased options. :param alias: The name of the aliased options. :param target: Get alias for this specific target (optional). If no matching alias is found, returns ``None``.
[ "Get", "a", "dictionary", "of", "aliased", "options", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L47-L59
8,732
SmileyChris/easy-thumbnails
easy_thumbnails/alias.py
Aliases.all
def all(self, target=None, include_global=True): """ Get a dictionary of all aliases and their options. :param target: Include aliases for this specific field, model or app (optional). :param include_global: Include all non target-specific aliases (default ``True...
python
def all(self, target=None, include_global=True): """ Get a dictionary of all aliases and their options. :param target: Include aliases for this specific field, model or app (optional). :param include_global: Include all non target-specific aliases (default ``True...
[ "def", "all", "(", "self", ",", "target", "=", "None", ",", "include_global", "=", "True", ")", ":", "aliases", "=", "{", "}", "for", "target_part", "in", "self", ".", "_get_targets", "(", "target", ",", "include_global", ")", ":", "aliases", ".", "upd...
Get a dictionary of all aliases and their options. :param target: Include aliases for this specific field, model or app (optional). :param include_global: Include all non target-specific aliases (default ``True``). For example:: >>> aliases.all(target='my_a...
[ "Get", "a", "dictionary", "of", "all", "aliases", "and", "their", "options", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L61-L78
8,733
SmileyChris/easy-thumbnails
easy_thumbnails/alias.py
Aliases._get
def _get(self, target, alias): """ Internal method to get a specific alias. """ if target not in self._aliases: return return self._aliases[target].get(alias)
python
def _get(self, target, alias): """ Internal method to get a specific alias. """ if target not in self._aliases: return return self._aliases[target].get(alias)
[ "def", "_get", "(", "self", ",", "target", ",", "alias", ")", ":", "if", "target", "not", "in", "self", ".", "_aliases", ":", "return", "return", "self", ".", "_aliases", "[", "target", "]", ".", "get", "(", "alias", ")" ]
Internal method to get a specific alias.
[ "Internal", "method", "to", "get", "a", "specific", "alias", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L80-L86
8,734
SmileyChris/easy-thumbnails
easy_thumbnails/alias.py
Aliases._get_targets
def _get_targets(self, target, include_global=True): """ Internal iterator to split up a complete target into the possible parts it may match. For example:: >>> list(aliases._get_targets('my_app.MyModel.somefield')) ['', 'my_app', 'my_app.MyModel', 'my_app.MyMod...
python
def _get_targets(self, target, include_global=True): """ Internal iterator to split up a complete target into the possible parts it may match. For example:: >>> list(aliases._get_targets('my_app.MyModel.somefield')) ['', 'my_app', 'my_app.MyModel', 'my_app.MyMod...
[ "def", "_get_targets", "(", "self", ",", "target", ",", "include_global", "=", "True", ")", ":", "target", "=", "self", ".", "_coerce_target", "(", "target", ")", "if", "include_global", ":", "yield", "''", "if", "not", "target", ":", "return", "target_bit...
Internal iterator to split up a complete target into the possible parts it may match. For example:: >>> list(aliases._get_targets('my_app.MyModel.somefield')) ['', 'my_app', 'my_app.MyModel', 'my_app.MyModel.somefield']
[ "Internal", "iterator", "to", "split", "up", "a", "complete", "target", "into", "the", "possible", "parts", "it", "may", "match", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L88-L105
8,735
SmileyChris/easy-thumbnails
easy_thumbnails/alias.py
Aliases._coerce_target
def _coerce_target(self, target): """ Internal method to coerce a target to a string. The assumption is that if it is not ``None`` and not a string, it is a Django ``FieldFile`` object. """ if not target or isinstance(target, six.string_types): return target ...
python
def _coerce_target(self, target): """ Internal method to coerce a target to a string. The assumption is that if it is not ``None`` and not a string, it is a Django ``FieldFile`` object. """ if not target or isinstance(target, six.string_types): return target ...
[ "def", "_coerce_target", "(", "self", ",", "target", ")", ":", "if", "not", "target", "or", "isinstance", "(", "target", ",", "six", ".", "string_types", ")", ":", "return", "target", "if", "not", "hasattr", "(", "target", ",", "'instance'", ")", ":", ...
Internal method to coerce a target to a string. The assumption is that if it is not ``None`` and not a string, it is a Django ``FieldFile`` object.
[ "Internal", "method", "to", "coerce", "a", "target", "to", "a", "string", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L107-L128
8,736
SmileyChris/easy-thumbnails
easy_thumbnails/utils.py
image_entropy
def image_entropy(im): """ Calculate the entropy of an image. Used for "smart cropping". """ if not isinstance(im, Image.Image): # Can only deal with PIL images. Fall back to a constant entropy. return 0 hist = im.histogram() hist_size = float(sum(hist)) hist = [h / hist_size...
python
def image_entropy(im): """ Calculate the entropy of an image. Used for "smart cropping". """ if not isinstance(im, Image.Image): # Can only deal with PIL images. Fall back to a constant entropy. return 0 hist = im.histogram() hist_size = float(sum(hist)) hist = [h / hist_size...
[ "def", "image_entropy", "(", "im", ")", ":", "if", "not", "isinstance", "(", "im", ",", "Image", ".", "Image", ")", ":", "# Can only deal with PIL images. Fall back to a constant entropy.", "return", "0", "hist", "=", "im", ".", "histogram", "(", ")", "hist_size...
Calculate the entropy of an image. Used for "smart cropping".
[ "Calculate", "the", "entropy", "of", "an", "image", ".", "Used", "for", "smart", "cropping", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L18-L28
8,737
SmileyChris/easy-thumbnails
easy_thumbnails/utils.py
dynamic_import
def dynamic_import(import_string): """ Dynamically import a module or object. """ # Use rfind rather than rsplit for Python 2.3 compatibility. lastdot = import_string.rfind('.') if lastdot == -1: return __import__(import_string, {}, {}, []) module_name, attr = import_string[:lastdot]...
python
def dynamic_import(import_string): """ Dynamically import a module or object. """ # Use rfind rather than rsplit for Python 2.3 compatibility. lastdot = import_string.rfind('.') if lastdot == -1: return __import__(import_string, {}, {}, []) module_name, attr = import_string[:lastdot]...
[ "def", "dynamic_import", "(", "import_string", ")", ":", "# Use rfind rather than rsplit for Python 2.3 compatibility.", "lastdot", "=", "import_string", ".", "rfind", "(", "'.'", ")", "if", "lastdot", "==", "-", "1", ":", "return", "__import__", "(", "import_string",...
Dynamically import a module or object.
[ "Dynamically", "import", "a", "module", "or", "object", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L31-L41
8,738
SmileyChris/easy-thumbnails
easy_thumbnails/utils.py
is_transparent
def is_transparent(image): """ Check to see if an image is transparent. """ if not isinstance(image, Image.Image): # Can only deal with PIL images, fall back to the assumption that that # it's not transparent. return False return (image.mode in ('RGBA', 'LA') or (...
python
def is_transparent(image): """ Check to see if an image is transparent. """ if not isinstance(image, Image.Image): # Can only deal with PIL images, fall back to the assumption that that # it's not transparent. return False return (image.mode in ('RGBA', 'LA') or (...
[ "def", "is_transparent", "(", "image", ")", ":", "if", "not", "isinstance", "(", "image", ",", "Image", ".", "Image", ")", ":", "# Can only deal with PIL images, fall back to the assumption that that", "# it's not transparent.", "return", "False", "return", "(", "image"...
Check to see if an image is transparent.
[ "Check", "to", "see", "if", "an", "image", "is", "transparent", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L89-L98
8,739
SmileyChris/easy-thumbnails
easy_thumbnails/utils.py
is_progressive
def is_progressive(image): """ Check to see if an image is progressive. """ if not isinstance(image, Image.Image): # Can only check PIL images for progressive encoding. return False return ('progressive' in image.info) or ('progression' in image.info)
python
def is_progressive(image): """ Check to see if an image is progressive. """ if not isinstance(image, Image.Image): # Can only check PIL images for progressive encoding. return False return ('progressive' in image.info) or ('progression' in image.info)
[ "def", "is_progressive", "(", "image", ")", ":", "if", "not", "isinstance", "(", "image", ",", "Image", ".", "Image", ")", ":", "# Can only check PIL images for progressive encoding.", "return", "False", "return", "(", "'progressive'", "in", "image", ".", "info", ...
Check to see if an image is progressive.
[ "Check", "to", "see", "if", "an", "image", "is", "progressive", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L101-L108
8,740
SmileyChris/easy-thumbnails
easy_thumbnails/utils.py
get_modified_time
def get_modified_time(storage, name): """ Get modified time from storage, ensuring the result is a timezone-aware datetime. """ try: try: # Prefer Django 1.10 API and fall back to old one modified_time = storage.get_modified_time(name) except AttributeError: ...
python
def get_modified_time(storage, name): """ Get modified time from storage, ensuring the result is a timezone-aware datetime. """ try: try: # Prefer Django 1.10 API and fall back to old one modified_time = storage.get_modified_time(name) except AttributeError: ...
[ "def", "get_modified_time", "(", "storage", ",", "name", ")", ":", "try", ":", "try", ":", "# Prefer Django 1.10 API and fall back to old one", "modified_time", "=", "storage", ".", "get_modified_time", "(", "name", ")", "except", "AttributeError", ":", "modified_time...
Get modified time from storage, ensuring the result is a timezone-aware datetime.
[ "Get", "modified", "time", "from", "storage", "ensuring", "the", "result", "is", "a", "timezone", "-", "aware", "datetime", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L140-L159
8,741
dr-leo/pandaSDMX
pandasdmx/utils/anynamedtuple.py
namedtuple
def namedtuple(typename, field_names, verbose=False, rename=False): """Returns a new subclass of tuple with named fields. This is a patched version of collections.namedtuple from the stdlib. Unlike the latter, it accepts non-identifier strings as field names. All values are accessible through dict synta...
python
def namedtuple(typename, field_names, verbose=False, rename=False): """Returns a new subclass of tuple with named fields. This is a patched version of collections.namedtuple from the stdlib. Unlike the latter, it accepts non-identifier strings as field names. All values are accessible through dict synta...
[ "def", "namedtuple", "(", "typename", ",", "field_names", ",", "verbose", "=", "False", ",", "rename", "=", "False", ")", ":", "if", "isinstance", "(", "field_names", ",", "str", ")", ":", "field_names", "=", "field_names", ".", "replace", "(", "','", ",...
Returns a new subclass of tuple with named fields. This is a patched version of collections.namedtuple from the stdlib. Unlike the latter, it accepts non-identifier strings as field names. All values are accessible through dict syntax. Fields whose names are identifiers are also accessible via attribute...
[ "Returns", "a", "new", "subclass", "of", "tuple", "with", "named", "fields", ".", "This", "is", "a", "patched", "version", "of", "collections", ".", "namedtuple", "from", "the", "stdlib", ".", "Unlike", "the", "latter", "it", "accepts", "non", "-", "identi...
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/utils/anynamedtuple.py#L89-L172
8,742
dr-leo/pandaSDMX
pandasdmx/reader/sdmxjson.py
Reader.write_source
def write_source(self, filename): ''' Save source to file by calling `write` on the root element. ''' with open(filename, 'w') as fp: return json.dump(self.message._elem, fp, indent=4, sort_keys=True)
python
def write_source(self, filename): ''' Save source to file by calling `write` on the root element. ''' with open(filename, 'w') as fp: return json.dump(self.message._elem, fp, indent=4, sort_keys=True)
[ "def", "write_source", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fp", ":", "return", "json", ".", "dump", "(", "self", ".", "message", ".", "_elem", ",", "fp", ",", "indent", "=", "4", ",", "...
Save source to file by calling `write` on the root element.
[ "Save", "source", "to", "file", "by", "calling", "write", "on", "the", "root", "element", "." ]
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/sdmxjson.py#L86-L91
8,743
dr-leo/pandaSDMX
pandasdmx/reader/sdmxml.py
Reader.write_source
def write_source(self, filename): ''' Save XML source to file by calling `write` on the root element. ''' return self.message._elem.getroottree().write(filename, encoding='utf8')
python
def write_source(self, filename): ''' Save XML source to file by calling `write` on the root element. ''' return self.message._elem.getroottree().write(filename, encoding='utf8')
[ "def", "write_source", "(", "self", ",", "filename", ")", ":", "return", "self", ".", "message", ".", "_elem", ".", "getroottree", "(", ")", ".", "write", "(", "filename", ",", "encoding", "=", "'utf8'", ")" ]
Save XML source to file by calling `write` on the root element.
[ "Save", "XML", "source", "to", "file", "by", "calling", "write", "on", "the", "root", "element", "." ]
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/sdmxml.py#L52-L56
8,744
dr-leo/pandaSDMX
pandasdmx/model.py
Series.group_attrib
def group_attrib(self): ''' return a namedtuple containing all attributes attached to groups of which the given series is a member for each group of which the series is a member ''' group_attributes = [g.attrib for g in self.dataset.groups if self in g] if ...
python
def group_attrib(self): ''' return a namedtuple containing all attributes attached to groups of which the given series is a member for each group of which the series is a member ''' group_attributes = [g.attrib for g in self.dataset.groups if self in g] if ...
[ "def", "group_attrib", "(", "self", ")", ":", "group_attributes", "=", "[", "g", ".", "attrib", "for", "g", "in", "self", ".", "dataset", ".", "groups", "if", "self", "in", "g", "]", "if", "group_attributes", ":", "return", "concat_namedtuples", "(", "*"...
return a namedtuple containing all attributes attached to groups of which the given series is a member for each group of which the series is a member
[ "return", "a", "namedtuple", "containing", "all", "attributes", "attached", "to", "groups", "of", "which", "the", "given", "series", "is", "a", "member", "for", "each", "group", "of", "which", "the", "series", "is", "a", "member" ]
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/model.py#L632-L640
8,745
dr-leo/pandaSDMX
pandasdmx/reader/__init__.py
BaseReader.read_instance
def read_instance(self, cls, sdmxobj, offset=None, first_only=True): ''' If cls in _paths and matches, return an instance of cls with the first XML element, or, if first_only is False, a list of cls instances for all elements found, If no matches were found, return...
python
def read_instance(self, cls, sdmxobj, offset=None, first_only=True): ''' If cls in _paths and matches, return an instance of cls with the first XML element, or, if first_only is False, a list of cls instances for all elements found, If no matches were found, return...
[ "def", "read_instance", "(", "self", ",", "cls", ",", "sdmxobj", ",", "offset", "=", "None", ",", "first_only", "=", "True", ")", ":", "if", "offset", ":", "try", ":", "base", "=", "self", ".", "_paths", "[", "offset", "]", "(", "sdmxobj", ".", "_e...
If cls in _paths and matches, return an instance of cls with the first XML element, or, if first_only is False, a list of cls instances for all elements found, If no matches were found, return None.
[ "If", "cls", "in", "_paths", "and", "matches", "return", "an", "instance", "of", "cls", "with", "the", "first", "XML", "element", "or", "if", "first_only", "is", "False", "a", "list", "of", "cls", "instances", "for", "all", "elements", "found", "If", "no...
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/__init__.py#L54-L74
8,746
dr-leo/pandaSDMX
pandasdmx/api.py
Request.load_agency_profile
def load_agency_profile(cls, source): ''' Classmethod loading metadata on a data provider. ``source`` must be a json-formated string or file-like object describing one or more data providers (URL of the SDMX web API, resource types etc. The dict ``Request._agencies`` is updated w...
python
def load_agency_profile(cls, source): ''' Classmethod loading metadata on a data provider. ``source`` must be a json-formated string or file-like object describing one or more data providers (URL of the SDMX web API, resource types etc. The dict ``Request._agencies`` is updated w...
[ "def", "load_agency_profile", "(", "cls", ",", "source", ")", ":", "if", "not", "isinstance", "(", "source", ",", "str_type", ")", ":", "# so it must be a text file", "source", "=", "source", ".", "read", "(", ")", "new_agencies", "=", "json", ".", "loads", ...
Classmethod loading metadata on a data provider. ``source`` must be a json-formated string or file-like object describing one or more data providers (URL of the SDMX web API, resource types etc. The dict ``Request._agencies`` is updated with the metadata from the source. Returns...
[ "Classmethod", "loading", "metadata", "on", "a", "data", "provider", ".", "source", "must", "be", "a", "json", "-", "formated", "string", "or", "file", "-", "like", "object", "describing", "one", "or", "more", "data", "providers", "(", "URL", "of", "the", ...
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L63-L77
8,747
dr-leo/pandaSDMX
pandasdmx/api.py
Request.series_keys
def series_keys(self, flow_id, cache=True): ''' Get an empty dataset with all possible series keys. Return a pandas DataFrame. Each column represents a dimension, each row a series key of datasets of the given dataflow. ''' # Check if requested series ke...
python
def series_keys(self, flow_id, cache=True): ''' Get an empty dataset with all possible series keys. Return a pandas DataFrame. Each column represents a dimension, each row a series key of datasets of the given dataflow. ''' # Check if requested series ke...
[ "def", "series_keys", "(", "self", ",", "flow_id", ",", "cache", "=", "True", ")", ":", "# Check if requested series keys are already cached", "cache_id", "=", "'series_keys_'", "+", "flow_id", "if", "cache_id", "in", "self", ".", "cache", ":", "return", "self", ...
Get an empty dataset with all possible series keys. Return a pandas DataFrame. Each column represents a dimension, each row a series key of datasets of the given dataflow.
[ "Get", "an", "empty", "dataset", "with", "all", "possible", "series", "keys", "." ]
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L150-L170
8,748
dr-leo/pandaSDMX
pandasdmx/api.py
Request.preview_data
def preview_data(self, flow_id, key=None, count=True, total=True): ''' Get keys or number of series for a prospective dataset query allowing for keys with multiple values per dimension. It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. Th...
python
def preview_data(self, flow_id, key=None, count=True, total=True): ''' Get keys or number of series for a prospective dataset query allowing for keys with multiple values per dimension. It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. Th...
[ "def", "preview_data", "(", "self", ",", "flow_id", ",", "key", "=", "None", ",", "count", "=", "True", ",", "total", "=", "True", ")", ":", "all_keys", "=", "self", ".", "series_keys", "(", "flow_id", ")", "# Handle the special case that no key is provided", ...
Get keys or number of series for a prospective dataset query allowing for keys with multiple values per dimension. It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. This feature is, however, not supported by all data providers. ECB and UN...
[ "Get", "keys", "or", "number", "of", "series", "for", "a", "prospective", "dataset", "query", "allowing", "for", "keys", "with", "multiple", "values", "per", "dimension", ".", "It", "downloads", "the", "complete", "list", "of", "series", "keys", "for", "a", ...
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L495-L564
8,749
dr-leo/pandaSDMX
pandasdmx/api.py
Response.write
def write(self, source=None, **kwargs): '''Wrappe r to call the writer's write method if present. Args: source(pandasdmx.model.Message, iterable): stuff to be written. If a :class:`pandasdmx.model.Message` is given, the writer itself must determine what to...
python
def write(self, source=None, **kwargs): '''Wrappe r to call the writer's write method if present. Args: source(pandasdmx.model.Message, iterable): stuff to be written. If a :class:`pandasdmx.model.Message` is given, the writer itself must determine what to...
[ "def", "write", "(", "self", ",", "source", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "source", ":", "source", "=", "self", ".", "msg", "return", "self", ".", "_writer", ".", "write", "(", "source", "=", "source", ",", "*", "*"...
Wrappe r to call the writer's write method if present. Args: source(pandasdmx.model.Message, iterable): stuff to be written. If a :class:`pandasdmx.model.Message` is given, the writer itself must determine what to write unless specified in the keyw...
[ "Wrappe", "r", "to", "call", "the", "writer", "s", "write", "method", "if", "present", "." ]
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L618-L635
8,750
dropbox/pyannotate
pyannotate_tools/annotations/parse.py
parse_json
def parse_json(path): # type: (str) -> List[FunctionInfo] """Deserialize a JSON file containing runtime collected types. The input JSON is expected to to have a list of RawEntry items. """ with open(path) as f: data = json.load(f) # type: List[RawEntry] result = [] def assert_type...
python
def parse_json(path): # type: (str) -> List[FunctionInfo] """Deserialize a JSON file containing runtime collected types. The input JSON is expected to to have a list of RawEntry items. """ with open(path) as f: data = json.load(f) # type: List[RawEntry] result = [] def assert_type...
[ "def", "parse_json", "(", "path", ")", ":", "# type: (str) -> List[FunctionInfo]", "with", "open", "(", "path", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "# type: List[RawEntry]", "result", "=", "[", "]", "def", "assert_type", "...
Deserialize a JSON file containing runtime collected types. The input JSON is expected to to have a list of RawEntry items.
[ "Deserialize", "a", "JSON", "file", "containing", "runtime", "collected", "types", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/parse.py#L96-L133
8,751
dropbox/pyannotate
pyannotate_tools/annotations/parse.py
tokenize
def tokenize(s): # type: (str) -> List[Token] """Translate a type comment into a list of tokens.""" original = s tokens = [] # type: List[Token] while True: if not s: tokens.append(End()) return tokens elif s[0] == ' ': s = s[1:] elif s[0]...
python
def tokenize(s): # type: (str) -> List[Token] """Translate a type comment into a list of tokens.""" original = s tokens = [] # type: List[Token] while True: if not s: tokens.append(End()) return tokens elif s[0] == ' ': s = s[1:] elif s[0]...
[ "def", "tokenize", "(", "s", ")", ":", "# type: (str) -> List[Token]", "original", "=", "s", "tokens", "=", "[", "]", "# type: List[Token]", "while", "True", ":", "if", "not", "s", ":", "tokens", ".", "append", "(", "End", "(", ")", ")", "return", "token...
Translate a type comment into a list of tokens.
[ "Translate", "a", "type", "comment", "into", "a", "list", "of", "tokens", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/parse.py#L173-L210
8,752
dropbox/pyannotate
pyannotate_tools/annotations/main.py
generate_annotations_json_string
def generate_annotations_json_string(source_path, only_simple=False): # type: (str, bool) -> List[FunctionData] """Produce annotation data JSON file from a JSON file with runtime-collected types. Data formats: * The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items. * The ...
python
def generate_annotations_json_string(source_path, only_simple=False): # type: (str, bool) -> List[FunctionData] """Produce annotation data JSON file from a JSON file with runtime-collected types. Data formats: * The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items. * The ...
[ "def", "generate_annotations_json_string", "(", "source_path", ",", "only_simple", "=", "False", ")", ":", "# type: (str, bool) -> List[FunctionData]", "items", "=", "parse_json", "(", "source_path", ")", "results", "=", "[", "]", "for", "item", "in", "items", ":", ...
Produce annotation data JSON file from a JSON file with runtime-collected types. Data formats: * The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items. * The output JSON is a list of FunctionData items.
[ "Produce", "annotation", "data", "JSON", "file", "from", "a", "JSON", "file", "with", "runtime", "-", "collected", "types", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/main.py#L48-L70
8,753
dropbox/pyannotate
pyannotate_runtime/collect_types.py
_my_hash
def _my_hash(arg_list): # type: (List[Any]) -> int """Simple helper hash function""" res = 0 for arg in arg_list: res = res * 31 + hash(arg) return res
python
def _my_hash(arg_list): # type: (List[Any]) -> int """Simple helper hash function""" res = 0 for arg in arg_list: res = res * 31 + hash(arg) return res
[ "def", "_my_hash", "(", "arg_list", ")", ":", "# type: (List[Any]) -> int", "res", "=", "0", "for", "arg", "in", "arg_list", ":", "res", "=", "res", "*", "31", "+", "hash", "(", "arg", ")", "return", "res" ]
Simple helper hash function
[ "Simple", "helper", "hash", "function" ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L69-L75
8,754
dropbox/pyannotate
pyannotate_runtime/collect_types.py
name_from_type
def name_from_type(type_): # type: (InternalType) -> str """ Helper function to get PEP-484 compatible string representation of our internal types. """ if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)): return repr(type_) else: if type_.__name__ != 'Non...
python
def name_from_type(type_): # type: (InternalType) -> str """ Helper function to get PEP-484 compatible string representation of our internal types. """ if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)): return repr(type_) else: if type_.__name__ != 'Non...
[ "def", "name_from_type", "(", "type_", ")", ":", "# type: (InternalType) -> str", "if", "isinstance", "(", "type_", ",", "(", "DictType", ",", "ListType", ",", "TupleType", ",", "SetType", ",", "IteratorType", ")", ")", ":", "return", "repr", "(", "type_", "...
Helper function to get PEP-484 compatible string representation of our internal types.
[ "Helper", "function", "to", "get", "PEP", "-", "484", "compatible", "string", "representation", "of", "our", "internal", "types", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L417-L437
8,755
dropbox/pyannotate
pyannotate_runtime/collect_types.py
resolve_type
def resolve_type(arg): # type: (object) -> InternalType """ Resolve object to one of our internal collection types or generic built-in type. Args: arg: object to resolve """ arg_type = type(arg) if arg_type == list: assert isinstance(arg, list) # this line helps mypy figure...
python
def resolve_type(arg): # type: (object) -> InternalType """ Resolve object to one of our internal collection types or generic built-in type. Args: arg: object to resolve """ arg_type = type(arg) if arg_type == list: assert isinstance(arg, list) # this line helps mypy figure...
[ "def", "resolve_type", "(", "arg", ")", ":", "# type: (object) -> InternalType", "arg_type", "=", "type", "(", "arg", ")", "if", "arg_type", "==", "list", ":", "assert", "isinstance", "(", "arg", ",", "list", ")", "# this line helps mypy figure out types", "sample...
Resolve object to one of our internal collection types or generic built-in type. Args: arg: object to resolve
[ "Resolve", "object", "to", "one", "of", "our", "internal", "collection", "types", "or", "generic", "built", "-", "in", "type", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L498-L549
8,756
dropbox/pyannotate
pyannotate_runtime/collect_types.py
prep_args
def prep_args(arg_info): # type: (ArgInfo) -> ResolvedTypes """ Resolve types from ArgInfo """ # pull out any varargs declarations filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a] # we don't care about self/cls first params (perhaps we can test if it's ...
python
def prep_args(arg_info): # type: (ArgInfo) -> ResolvedTypes """ Resolve types from ArgInfo """ # pull out any varargs declarations filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a] # we don't care about self/cls first params (perhaps we can test if it's ...
[ "def", "prep_args", "(", "arg_info", ")", ":", "# type: (ArgInfo) -> ResolvedTypes", "# pull out any varargs declarations", "filtered_args", "=", "[", "a", "for", "a", "in", "arg_info", ".", "args", "if", "getattr", "(", "arg_info", ",", "'varargs'", ",", "None", ...
Resolve types from ArgInfo
[ "Resolve", "types", "from", "ArgInfo" ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L552-L583
8,757
dropbox/pyannotate
pyannotate_runtime/collect_types.py
_flush_signature
def _flush_signature(key, return_type): # type: (FunctionKey, InternalType) -> None """Store signature for a function. Assume that argument types have been stored previously to 'collected_args'. As the 'return_type' argument provides the return type, we now have a complete signature. As a side...
python
def _flush_signature(key, return_type): # type: (FunctionKey, InternalType) -> None """Store signature for a function. Assume that argument types have been stored previously to 'collected_args'. As the 'return_type' argument provides the return type, we now have a complete signature. As a side...
[ "def", "_flush_signature", "(", "key", ",", "return_type", ")", ":", "# type: (FunctionKey, InternalType) -> None", "signatures", "=", "collected_signatures", ".", "setdefault", "(", "key", ",", "set", "(", ")", ")", "args_info", "=", "collected_args", ".", "pop", ...
Store signature for a function. Assume that argument types have been stored previously to 'collected_args'. As the 'return_type' argument provides the return type, we now have a complete signature. As a side effect, removes the argument types for the function from 'collected_args'.
[ "Store", "signature", "for", "a", "function", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L656-L671
8,758
dropbox/pyannotate
pyannotate_runtime/collect_types.py
type_consumer
def type_consumer(): # type: () -> None """ Infinite loop of the type consumer thread. It gets types to process from the task query. """ # we are not interested in profiling type_consumer itself # but we start it before any other thread while True: item = _task_queue.get() ...
python
def type_consumer(): # type: () -> None """ Infinite loop of the type consumer thread. It gets types to process from the task query. """ # we are not interested in profiling type_consumer itself # but we start it before any other thread while True: item = _task_queue.get() ...
[ "def", "type_consumer", "(", ")", ":", "# type: () -> None", "# we are not interested in profiling type_consumer itself", "# but we start it before any other thread", "while", "True", ":", "item", "=", "_task_queue", ".", "get", "(", ")", "if", "isinstance", "(", "item", ...
Infinite loop of the type consumer thread. It gets types to process from the task query.
[ "Infinite", "loop", "of", "the", "type", "consumer", "thread", ".", "It", "gets", "types", "to", "process", "from", "the", "task", "query", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L674-L696
8,759
dropbox/pyannotate
pyannotate_runtime/collect_types.py
_make_sampling_sequence
def _make_sampling_sequence(n): # type: (int) -> List[int] """ Return a list containing the proposed call event sampling sequence. Return events are paired with call events and not counted separately. This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc. The total list size is n. """ s...
python
def _make_sampling_sequence(n): # type: (int) -> List[int] """ Return a list containing the proposed call event sampling sequence. Return events are paired with call events and not counted separately. This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc. The total list size is n. """ s...
[ "def", "_make_sampling_sequence", "(", "n", ")", ":", "# type: (int) -> List[int]", "seq", "=", "list", "(", "range", "(", "5", ")", ")", "i", "=", "50", "while", "len", "(", "seq", ")", "<", "n", ":", "seq", ".", "append", "(", "i", ")", "i", "+="...
Return a list containing the proposed call event sampling sequence. Return events are paired with call events and not counted separately. This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc. The total list size is n.
[ "Return", "a", "list", "containing", "the", "proposed", "call", "event", "sampling", "sequence", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L711-L727
8,760
dropbox/pyannotate
pyannotate_runtime/collect_types.py
default_filter_filename
def default_filter_filename(filename): # type: (Optional[str]) -> Optional[str] """Default filter for filenames. Returns either a normalized filename or None. You can pass your own filter to init_types_collection(). """ if filename is None: return None elif filename.startswith(TOP_D...
python
def default_filter_filename(filename): # type: (Optional[str]) -> Optional[str] """Default filter for filenames. Returns either a normalized filename or None. You can pass your own filter to init_types_collection(). """ if filename is None: return None elif filename.startswith(TOP_D...
[ "def", "default_filter_filename", "(", "filename", ")", ":", "# type: (Optional[str]) -> Optional[str]", "if", "filename", "is", "None", ":", "return", "None", "elif", "filename", ".", "startswith", "(", "TOP_DIR", ")", ":", "if", "filename", ".", "startswith", "(...
Default filter for filenames. Returns either a normalized filename or None. You can pass your own filter to init_types_collection().
[ "Default", "filter", "for", "filenames", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L787-L807
8,761
dropbox/pyannotate
pyannotate_runtime/collect_types.py
_filter_types
def _filter_types(types_dict): # type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T] """Filter type info before dumping it to the file.""" def exclude(k): # type: (FunctionKey) -> bool """Exclude filter""" return k.path.startswith('<') or k.func_name == '<module>' return {k: v...
python
def _filter_types(types_dict): # type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T] """Filter type info before dumping it to the file.""" def exclude(k): # type: (FunctionKey) -> bool """Exclude filter""" return k.path.startswith('<') or k.func_name == '<module>' return {k: v...
[ "def", "_filter_types", "(", "types_dict", ")", ":", "# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]", "def", "exclude", "(", "k", ")", ":", "# type: (FunctionKey) -> bool", "\"\"\"Exclude filter\"\"\"", "return", "k", ".", "path", ".", "startswith", "(", "'<'", ...
Filter type info before dumping it to the file.
[ "Filter", "type", "info", "before", "dumping", "it", "to", "the", "file", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L909-L918
8,762
dropbox/pyannotate
pyannotate_runtime/collect_types.py
_dump_impl
def _dump_impl(): # type: () -> List[FunctionData] """Internal implementation for dump_stats and dumps_stats""" filtered_signatures = _filter_types(collected_signatures) sorted_by_file = sorted(iteritems(filtered_signatures), key=(lambda p: (p[0].path, p[0].line, p[0].func_na...
python
def _dump_impl(): # type: () -> List[FunctionData] """Internal implementation for dump_stats and dumps_stats""" filtered_signatures = _filter_types(collected_signatures) sorted_by_file = sorted(iteritems(filtered_signatures), key=(lambda p: (p[0].path, p[0].line, p[0].func_na...
[ "def", "_dump_impl", "(", ")", ":", "# type: () -> List[FunctionData]", "filtered_signatures", "=", "_filter_types", "(", "collected_signatures", ")", "sorted_by_file", "=", "sorted", "(", "iteritems", "(", "filtered_signatures", ")", ",", "key", "=", "(", "lambda", ...
Internal implementation for dump_stats and dumps_stats
[ "Internal", "implementation", "for", "dump_stats", "and", "dumps_stats" ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L921-L939
8,763
dropbox/pyannotate
pyannotate_runtime/collect_types.py
dump_stats
def dump_stats(filename): # type: (str) -> None """ Write collected information to file. Args: filename: absolute filename """ res = _dump_impl() f = open(filename, 'w') json.dump(res, f, indent=4) f.close()
python
def dump_stats(filename): # type: (str) -> None """ Write collected information to file. Args: filename: absolute filename """ res = _dump_impl() f = open(filename, 'w') json.dump(res, f, indent=4) f.close()
[ "def", "dump_stats", "(", "filename", ")", ":", "# type: (str) -> None", "res", "=", "_dump_impl", "(", ")", "f", "=", "open", "(", "filename", ",", "'w'", ")", "json", ".", "dump", "(", "res", ",", "f", ",", "indent", "=", "4", ")", "f", ".", "clo...
Write collected information to file. Args: filename: absolute filename
[ "Write", "collected", "information", "to", "file", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L942-L953
8,764
dropbox/pyannotate
pyannotate_runtime/collect_types.py
init_types_collection
def init_types_collection(filter_filename=default_filter_filename): # type: (Callable[[Optional[str]], Optional[str]]) -> None """ Setup profiler hooks to enable type collection. Call this one time from the main thread. The optional argument is a filter that maps a filename (from code.co_filena...
python
def init_types_collection(filter_filename=default_filter_filename): # type: (Callable[[Optional[str]], Optional[str]]) -> None """ Setup profiler hooks to enable type collection. Call this one time from the main thread. The optional argument is a filter that maps a filename (from code.co_filena...
[ "def", "init_types_collection", "(", "filter_filename", "=", "default_filter_filename", ")", ":", "# type: (Callable[[Optional[str]], Optional[str]]) -> None", "global", "_filter_filename", "_filter_filename", "=", "filter_filename", "sys", ".", "setprofile", "(", "_trace_dispatc...
Setup profiler hooks to enable type collection. Call this one time from the main thread. The optional argument is a filter that maps a filename (from code.co_filename) to either a normalized filename or None. For the default filter see default_filter_filename().
[ "Setup", "profiler", "hooks", "to", "enable", "type", "collection", ".", "Call", "this", "one", "time", "from", "the", "main", "thread", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L965-L978
8,765
dropbox/pyannotate
pyannotate_runtime/collect_types.py
TentativeType.add
def add(self, type): # type: (InternalType) -> None """ Add type to the runtime type samples. """ try: if isinstance(type, SetType): if EMPTY_SET_TYPE in self.types_hashable: self.types_hashable.remove(EMPTY_SET_TYPE) el...
python
def add(self, type): # type: (InternalType) -> None """ Add type to the runtime type samples. """ try: if isinstance(type, SetType): if EMPTY_SET_TYPE in self.types_hashable: self.types_hashable.remove(EMPTY_SET_TYPE) el...
[ "def", "add", "(", "self", ",", "type", ")", ":", "# type: (InternalType) -> None", "try", ":", "if", "isinstance", "(", "type", ",", "SetType", ")", ":", "if", "EMPTY_SET_TYPE", "in", "self", ".", "types_hashable", ":", "self", ".", "types_hashable", ".", ...
Add type to the runtime type samples.
[ "Add", "type", "to", "the", "runtime", "type", "samples", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L336-L367
8,766
dropbox/pyannotate
pyannotate_runtime/collect_types.py
TentativeType.merge
def merge(self, other): # type: (TentativeType) -> None """ Merge two TentativeType instances """ for hashables in other.types_hashable: self.add(hashables) for non_hashbles in other.types: self.add(non_hashbles)
python
def merge(self, other): # type: (TentativeType) -> None """ Merge two TentativeType instances """ for hashables in other.types_hashable: self.add(hashables) for non_hashbles in other.types: self.add(non_hashbles)
[ "def", "merge", "(", "self", ",", "other", ")", ":", "# type: (TentativeType) -> None", "for", "hashables", "in", "other", ".", "types_hashable", ":", "self", ".", "add", "(", "hashables", ")", "for", "non_hashbles", "in", "other", ".", "types", ":", "self",...
Merge two TentativeType instances
[ "Merge", "two", "TentativeType", "instances" ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L369-L377
8,767
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
infer_annotation
def infer_annotation(type_comments): # type: (List[str]) -> Tuple[List[Argument], AbstractType] """Given some type comments, return a single inferred signature. Args: type_comments: Strings of form '(arg1, ... argN) -> ret' Returns: Tuple of (argument types and kinds, return type). """ ...
python
def infer_annotation(type_comments): # type: (List[str]) -> Tuple[List[Argument], AbstractType] """Given some type comments, return a single inferred signature. Args: type_comments: Strings of form '(arg1, ... argN) -> ret' Returns: Tuple of (argument types and kinds, return type). """ ...
[ "def", "infer_annotation", "(", "type_comments", ")", ":", "# type: (List[str]) -> Tuple[List[Argument], AbstractType]", "assert", "type_comments", "args", "=", "{", "}", "# type: Dict[int, Set[Argument]]", "returns", "=", "set", "(", ")", "for", "comment", "in", "type_co...
Given some type comments, return a single inferred signature. Args: type_comments: Strings of form '(arg1, ... argN) -> ret' Returns: Tuple of (argument types and kinds, return type).
[ "Given", "some", "type", "comments", "return", "a", "single", "inferred", "signature", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L32-L66
8,768
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
argument_kind
def argument_kind(args): # type: (List[Argument]) -> Optional[str] """Return the kind of an argument, based on one or more descriptions of the argument. Return None if every item does not have the same kind. """ kinds = set(arg.kind for arg in args) if len(kinds) != 1: return None r...
python
def argument_kind(args): # type: (List[Argument]) -> Optional[str] """Return the kind of an argument, based on one or more descriptions of the argument. Return None if every item does not have the same kind. """ kinds = set(arg.kind for arg in args) if len(kinds) != 1: return None r...
[ "def", "argument_kind", "(", "args", ")", ":", "# type: (List[Argument]) -> Optional[str]", "kinds", "=", "set", "(", "arg", ".", "kind", "for", "arg", "in", "args", ")", "if", "len", "(", "kinds", ")", "!=", "1", ":", "return", "None", "return", "kinds", ...
Return the kind of an argument, based on one or more descriptions of the argument. Return None if every item does not have the same kind.
[ "Return", "the", "kind", "of", "an", "argument", "based", "on", "one", "or", "more", "descriptions", "of", "the", "argument", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L69-L78
8,769
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
combine_types
def combine_types(types): # type: (Iterable[AbstractType]) -> AbstractType """Given some types, return a combined and simplified type. For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given 'int' and 'int', return just 'int'. """ items = simplify_types(types) if...
python
def combine_types(types): # type: (Iterable[AbstractType]) -> AbstractType """Given some types, return a combined and simplified type. For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given 'int' and 'int', return just 'int'. """ items = simplify_types(types) if...
[ "def", "combine_types", "(", "types", ")", ":", "# type: (Iterable[AbstractType]) -> AbstractType", "items", "=", "simplify_types", "(", "types", ")", "if", "len", "(", "items", ")", "==", "1", ":", "return", "items", "[", "0", "]", "else", ":", "return", "U...
Given some types, return a combined and simplified type. For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given 'int' and 'int', return just 'int'.
[ "Given", "some", "types", "return", "a", "combined", "and", "simplified", "type", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L81-L92
8,770
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
simplify_types
def simplify_types(types): # type: (Iterable[AbstractType]) -> List[AbstractType] """Given some types, give simplified types representing the union of types.""" flattened = flatten_types(types) items = filter_ignored_items(flattened) items = [simplify_recursive(item) for item in items] items = m...
python
def simplify_types(types): # type: (Iterable[AbstractType]) -> List[AbstractType] """Given some types, give simplified types representing the union of types.""" flattened = flatten_types(types) items = filter_ignored_items(flattened) items = [simplify_recursive(item) for item in items] items = m...
[ "def", "simplify_types", "(", "types", ")", ":", "# type: (Iterable[AbstractType]) -> List[AbstractType]", "flattened", "=", "flatten_types", "(", "types", ")", "items", "=", "filter_ignored_items", "(", "flattened", ")", "items", "=", "[", "simplify_recursive", "(", ...
Given some types, give simplified types representing the union of types.
[ "Given", "some", "types", "give", "simplified", "types", "representing", "the", "union", "of", "types", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L95-L109
8,771
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
simplify_recursive
def simplify_recursive(typ): # type: (AbstractType) -> AbstractType """Simplify all components of a type.""" if isinstance(typ, UnionType): return combine_types(typ.items) elif isinstance(typ, ClassType): simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args]) ...
python
def simplify_recursive(typ): # type: (AbstractType) -> AbstractType """Simplify all components of a type.""" if isinstance(typ, UnionType): return combine_types(typ.items) elif isinstance(typ, ClassType): simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args]) ...
[ "def", "simplify_recursive", "(", "typ", ")", ":", "# type: (AbstractType) -> AbstractType", "if", "isinstance", "(", "typ", ",", "UnionType", ")", ":", "return", "combine_types", "(", "typ", ".", "items", ")", "elif", "isinstance", "(", "typ", ",", "ClassType",...
Simplify all components of a type.
[ "Simplify", "all", "components", "of", "a", "type", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L112-L128
8,772
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
remove_redundant_items
def remove_redundant_items(items): # type: (List[AbstractType]) -> List[AbstractType] """Filter out redundant union items.""" result = [] for item in items: for other in items: if item is not other and is_redundant_union_item(item, other): break else: ...
python
def remove_redundant_items(items): # type: (List[AbstractType]) -> List[AbstractType] """Filter out redundant union items.""" result = [] for item in items: for other in items: if item is not other and is_redundant_union_item(item, other): break else: ...
[ "def", "remove_redundant_items", "(", "items", ")", ":", "# type: (List[AbstractType]) -> List[AbstractType]", "result", "=", "[", "]", "for", "item", "in", "items", ":", "for", "other", "in", "items", ":", "if", "item", "is", "not", "other", "and", "is_redundan...
Filter out redundant union items.
[ "Filter", "out", "redundant", "union", "items", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L153-L163
8,773
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
is_redundant_union_item
def is_redundant_union_item(first, other): # type: (AbstractType, AbstractType) -> bool """If union has both items, is the first one redundant? For example, if first is 'str' and the other is 'Text', return True. If items are equal, return False. """ if isinstance(first, ClassType) and isinsta...
python
def is_redundant_union_item(first, other): # type: (AbstractType, AbstractType) -> bool """If union has both items, is the first one redundant? For example, if first is 'str' and the other is 'Text', return True. If items are equal, return False. """ if isinstance(first, ClassType) and isinsta...
[ "def", "is_redundant_union_item", "(", "first", ",", "other", ")", ":", "# type: (AbstractType, AbstractType) -> bool", "if", "isinstance", "(", "first", ",", "ClassType", ")", "and", "isinstance", "(", "other", ",", "ClassType", ")", ":", "if", "first", ".", "n...
If union has both items, is the first one redundant? For example, if first is 'str' and the other is 'Text', return True. If items are equal, return False.
[ "If", "union", "has", "both", "items", "is", "the", "first", "one", "redundant?" ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L166-L191
8,774
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
merge_items
def merge_items(items): # type: (List[AbstractType]) -> List[AbstractType] """Merge union items that can be merged.""" result = [] while items: item = items.pop() merged = None for i, other in enumerate(items): merged = merged_type(item, other) if merged: ...
python
def merge_items(items): # type: (List[AbstractType]) -> List[AbstractType] """Merge union items that can be merged.""" result = [] while items: item = items.pop() merged = None for i, other in enumerate(items): merged = merged_type(item, other) if merged: ...
[ "def", "merge_items", "(", "items", ")", ":", "# type: (List[AbstractType]) -> List[AbstractType]", "result", "=", "[", "]", "while", "items", ":", "item", "=", "items", ".", "pop", "(", ")", "merged", "=", "None", "for", "i", ",", "other", "in", "enumerate"...
Merge union items that can be merged.
[ "Merge", "union", "items", "that", "can", "be", "merged", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L194-L210
8,775
dropbox/pyannotate
pyannotate_tools/annotations/infer.py
merged_type
def merged_type(t, s): # type: (AbstractType, AbstractType) -> Optional[AbstractType] """Return merged type if two items can be merged in to a different, more general type. Return None if merging is not possible. """ if isinstance(t, TupleType) and isinstance(s, TupleType): if len(t.items) ...
python
def merged_type(t, s): # type: (AbstractType, AbstractType) -> Optional[AbstractType] """Return merged type if two items can be merged in to a different, more general type. Return None if merging is not possible. """ if isinstance(t, TupleType) and isinstance(s, TupleType): if len(t.items) ...
[ "def", "merged_type", "(", "t", ",", "s", ")", ":", "# type: (AbstractType, AbstractType) -> Optional[AbstractType]", "if", "isinstance", "(", "t", ",", "TupleType", ")", "and", "isinstance", "(", "s", ",", "TupleType", ")", ":", "if", "len", "(", "t", ".", ...
Return merged type if two items can be merged in to a different, more general type. Return None if merging is not possible.
[ "Return", "merged", "type", "if", "two", "items", "can", "be", "merged", "in", "to", "a", "different", "more", "general", "type", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L213-L243
8,776
dropbox/pyannotate
pyannotate_tools/annotations/__main__.py
dump_annotations
def dump_annotations(type_info, files): """Dump annotations out of type_info, filtered by files. If files is non-empty, only dump items either if the path in the item matches one of the files exactly, or else if one of the files is a path prefix of the path. """ with open(type_info) as f: ...
python
def dump_annotations(type_info, files): """Dump annotations out of type_info, filtered by files. If files is non-empty, only dump items either if the path in the item matches one of the files exactly, or else if one of the files is a path prefix of the path. """ with open(type_info) as f: ...
[ "def", "dump_annotations", "(", "type_info", ",", "files", ")", ":", "with", "open", "(", "type_info", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "for", "item", "in", "data", ":", "path", ",", "line", ",", "func_name", "=...
Dump annotations out of type_info, filtered by files. If files is non-empty, only dump items either if the path in the item matches one of the files exactly, or else if one of the files is a path prefix of the path.
[ "Dump", "annotations", "out", "of", "type_info", "filtered", "by", "files", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/__main__.py#L60-L82
8,777
dropbox/pyannotate
pyannotate_tools/fixes/fix_annotate_json.py
strip_py
def strip_py(arg): # type: (str) -> Optional[str] """Strip a trailing .py or .pyi suffix. Return None if no such suffix is found. """ for ext in PY_EXTENSIONS: if arg.endswith(ext): return arg[:-len(ext)] return None
python
def strip_py(arg): # type: (str) -> Optional[str] """Strip a trailing .py or .pyi suffix. Return None if no such suffix is found. """ for ext in PY_EXTENSIONS: if arg.endswith(ext): return arg[:-len(ext)] return None
[ "def", "strip_py", "(", "arg", ")", ":", "# type: (str) -> Optional[str]", "for", "ext", "in", "PY_EXTENSIONS", ":", "if", "arg", ".", "endswith", "(", "ext", ")", ":", "return", "arg", "[", ":", "-", "len", "(", "ext", ")", "]", "return", "None" ]
Strip a trailing .py or .pyi suffix. Return None if no such suffix is found.
[ "Strip", "a", "trailing", ".", "py", "or", ".", "pyi", "suffix", ".", "Return", "None", "if", "no", "such", "suffix", "is", "found", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate_json.py#L61-L69
8,778
dropbox/pyannotate
pyannotate_tools/fixes/fix_annotate.py
FixAnnotate.get_decorators
def get_decorators(self, node): """Return a list of decorators found on a function definition. This is a list of strings; only simple decorators (e.g. @staticmethod) are returned. If the function is undecorated or only non-simple decorators are found, return []. """ ...
python
def get_decorators(self, node): """Return a list of decorators found on a function definition. This is a list of strings; only simple decorators (e.g. @staticmethod) are returned. If the function is undecorated or only non-simple decorators are found, return []. """ ...
[ "def", "get_decorators", "(", "self", ",", "node", ")", ":", "if", "node", ".", "parent", "is", "None", ":", "return", "[", "]", "results", "=", "{", "}", "if", "not", "self", ".", "decorated", ".", "match", "(", "node", ".", "parent", ",", "result...
Return a list of decorators found on a function definition. This is a list of strings; only simple decorators (e.g. @staticmethod) are returned. If the function is undecorated or only non-simple decorators are found, return [].
[ "Return", "a", "list", "of", "decorators", "found", "on", "a", "function", "definition", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate.py#L418-L438
8,779
dropbox/pyannotate
pyannotate_tools/fixes/fix_annotate.py
FixAnnotate.has_return_exprs
def has_return_exprs(self, node): """Traverse the tree below node looking for 'return expr'. Return True if at least 'return expr' is found, False if not. (If both 'return' and 'return expr' are found, return True.) """ results = {} if self.return_expr.match(node, result...
python
def has_return_exprs(self, node): """Traverse the tree below node looking for 'return expr'. Return True if at least 'return expr' is found, False if not. (If both 'return' and 'return expr' are found, return True.) """ results = {} if self.return_expr.match(node, result...
[ "def", "has_return_exprs", "(", "self", ",", "node", ")", ":", "results", "=", "{", "}", "if", "self", ".", "return_expr", ".", "match", "(", "node", ",", "results", ")", ":", "return", "True", "for", "child", "in", "node", ".", "children", ":", "if"...
Traverse the tree below node looking for 'return expr'. Return True if at least 'return expr' is found, False if not. (If both 'return' and 'return expr' are found, return True.)
[ "Traverse", "the", "tree", "below", "node", "looking", "for", "return", "expr", "." ]
d128c76b8a86f208e5c78716f2a917003650cebc
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate.py#L454-L467
8,780
srsudar/eg
eg/config.py
inform_if_paths_invalid
def inform_if_paths_invalid(egrc_path, examples_dir, custom_dir, debug=True): """ If egrc_path, examples_dir, or custom_dir is truthy and debug is True, informs the user that a path is not set. This should be used to verify input arguments from the command line. """ if (not debug): retu...
python
def inform_if_paths_invalid(egrc_path, examples_dir, custom_dir, debug=True): """ If egrc_path, examples_dir, or custom_dir is truthy and debug is True, informs the user that a path is not set. This should be used to verify input arguments from the command line. """ if (not debug): retu...
[ "def", "inform_if_paths_invalid", "(", "egrc_path", ",", "examples_dir", ",", "custom_dir", ",", "debug", "=", "True", ")", ":", "if", "(", "not", "debug", ")", ":", "return", "if", "(", "egrc_path", ")", ":", "_inform_if_path_does_not_exist", "(", "egrc_path"...
If egrc_path, examples_dir, or custom_dir is truthy and debug is True, informs the user that a path is not set. This should be used to verify input arguments from the command line.
[ "If", "egrc_path", "examples_dir", "or", "custom_dir", "is", "truthy", "and", "debug", "is", "True", "informs", "the", "user", "that", "a", "path", "is", "not", "set", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L131-L148
8,781
srsudar/eg
eg/config.py
get_egrc_config
def get_egrc_config(cli_egrc_path): """ Return a Config namedtuple based on the contents of the egrc. If the egrc is not present, it returns an empty default Config. This method tries to use the egrc at cli_egrc_path, then the default path. cli_egrc_path: the path to the egrc as given on the comm...
python
def get_egrc_config(cli_egrc_path): """ Return a Config namedtuple based on the contents of the egrc. If the egrc is not present, it returns an empty default Config. This method tries to use the egrc at cli_egrc_path, then the default path. cli_egrc_path: the path to the egrc as given on the comm...
[ "def", "get_egrc_config", "(", "cli_egrc_path", ")", ":", "resolved_path", "=", "get_priority", "(", "cli_egrc_path", ",", "DEFAULT_EGRC_PATH", ",", "None", ")", "expanded_path", "=", "get_expanded_path", "(", "resolved_path", ")", "# Start as if nothing was defined in th...
Return a Config namedtuple based on the contents of the egrc. If the egrc is not present, it returns an empty default Config. This method tries to use the egrc at cli_egrc_path, then the default path. cli_egrc_path: the path to the egrc as given on the command line via --config-file
[ "Return", "a", "Config", "namedtuple", "based", "on", "the", "contents", "of", "the", "egrc", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L151-L171
8,782
srsudar/eg
eg/config.py
get_resolved_config
def get_resolved_config( egrc_path, examples_dir, custom_dir, use_color, pager_cmd, squeeze, debug=True, ): """ Create a Config namedtuple. Passed in values will override defaults. This function is responsible for producing a Config that is correct for the passed in argument...
python
def get_resolved_config( egrc_path, examples_dir, custom_dir, use_color, pager_cmd, squeeze, debug=True, ): """ Create a Config namedtuple. Passed in values will override defaults. This function is responsible for producing a Config that is correct for the passed in argument...
[ "def", "get_resolved_config", "(", "egrc_path", ",", "examples_dir", ",", "custom_dir", ",", "use_color", ",", "pager_cmd", ",", "squeeze", ",", "debug", "=", "True", ",", ")", ":", "# Call this with the passed in values, NOT the resolved values. We are", "# informing the...
Create a Config namedtuple. Passed in values will override defaults. This function is responsible for producing a Config that is correct for the passed in arguments. In general, it prefers first command line options, then values from the egrc, and finally defaults. examples_dir and custom_dir when ret...
[ "Create", "a", "Config", "namedtuple", ".", "Passed", "in", "values", "will", "override", "defaults", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L174-L276
8,783
srsudar/eg
eg/config.py
get_config_tuple_from_egrc
def get_config_tuple_from_egrc(egrc_path): """ Create a Config named tuple from the values specified in the .egrc. Expands any paths as necessary. egrc_path must exist and point a file. If not present in the .egrc, properties of the Config are returned as None. """ with open(egrc_path, 'r'...
python
def get_config_tuple_from_egrc(egrc_path): """ Create a Config named tuple from the values specified in the .egrc. Expands any paths as necessary. egrc_path must exist and point a file. If not present in the .egrc, properties of the Config are returned as None. """ with open(egrc_path, 'r'...
[ "def", "get_config_tuple_from_egrc", "(", "egrc_path", ")", ":", "with", "open", "(", "egrc_path", ",", "'r'", ")", "as", "egrc", ":", "try", ":", "config", "=", "ConfigParser", ".", "RawConfigParser", "(", ")", "except", "AttributeError", ":", "config", "="...
Create a Config named tuple from the values specified in the .egrc. Expands any paths as necessary. egrc_path must exist and point a file. If not present in the .egrc, properties of the Config are returned as None.
[ "Create", "a", "Config", "named", "tuple", "from", "the", "values", "specified", "in", "the", ".", "egrc", ".", "Expands", "any", "paths", "as", "necessary", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L279-L342
8,784
srsudar/eg
eg/config.py
get_expanded_path
def get_expanded_path(path): """Expand ~ and variables in a path. If path is not truthy, return None.""" if path: result = path result = os.path.expanduser(result) result = os.path.expandvars(result) return result else: return None
python
def get_expanded_path(path): """Expand ~ and variables in a path. If path is not truthy, return None.""" if path: result = path result = os.path.expanduser(result) result = os.path.expandvars(result) return result else: return None
[ "def", "get_expanded_path", "(", "path", ")", ":", "if", "path", ":", "result", "=", "path", "result", "=", "os", ".", "path", ".", "expanduser", "(", "result", ")", "result", "=", "os", ".", "path", ".", "expandvars", "(", "result", ")", "return", "...
Expand ~ and variables in a path. If path is not truthy, return None.
[ "Expand", "~", "and", "variables", "in", "a", "path", ".", "If", "path", "is", "not", "truthy", "return", "None", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L345-L353
8,785
srsudar/eg
eg/config.py
get_editor_cmd_from_environment
def get_editor_cmd_from_environment(): """ Gets and editor command from environment variables. It first tries $VISUAL, then $EDITOR, following the same order git uses when it looks up edits. If neither is available, it returns None. """ result = os.getenv(ENV_VISUAL) if (not result): ...
python
def get_editor_cmd_from_environment(): """ Gets and editor command from environment variables. It first tries $VISUAL, then $EDITOR, following the same order git uses when it looks up edits. If neither is available, it returns None. """ result = os.getenv(ENV_VISUAL) if (not result): ...
[ "def", "get_editor_cmd_from_environment", "(", ")", ":", "result", "=", "os", ".", "getenv", "(", "ENV_VISUAL", ")", "if", "(", "not", "result", ")", ":", "result", "=", "os", ".", "getenv", "(", "ENV_EDITOR", ")", "return", "result" ]
Gets and editor command from environment variables. It first tries $VISUAL, then $EDITOR, following the same order git uses when it looks up edits. If neither is available, it returns None.
[ "Gets", "and", "editor", "command", "from", "environment", "variables", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L356-L366
8,786
srsudar/eg
eg/config.py
_inform_if_path_does_not_exist
def _inform_if_path_does_not_exist(path): """ If the path does not exist, print a message saying so. This is intended to be helpful to users if they specify a custom path that eg cannot find. """ expanded_path = get_expanded_path(path) if not os.path.exists(expanded_path): print('Could n...
python
def _inform_if_path_does_not_exist(path): """ If the path does not exist, print a message saying so. This is intended to be helpful to users if they specify a custom path that eg cannot find. """ expanded_path = get_expanded_path(path) if not os.path.exists(expanded_path): print('Could n...
[ "def", "_inform_if_path_does_not_exist", "(", "path", ")", ":", "expanded_path", "=", "get_expanded_path", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "expanded_path", ")", ":", "print", "(", "'Could not find custom path at: {}'", ".", ...
If the path does not exist, print a message saying so. This is intended to be helpful to users if they specify a custom path that eg cannot find.
[ "If", "the", "path", "does", "not", "exist", "print", "a", "message", "saying", "so", ".", "This", "is", "intended", "to", "be", "helpful", "to", "users", "if", "they", "specify", "a", "custom", "path", "that", "eg", "cannot", "find", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L383-L390
8,787
srsudar/eg
eg/config.py
get_custom_color_config_from_egrc
def get_custom_color_config_from_egrc(config): """ Get the ColorConfig from the egrc config object. Any colors not defined will be None. """ pound = _get_color_from_config(config, CONFIG_NAMES.pound) heading = _get_color_from_config(config, CONFIG_NAMES.heading) code = _get_color_from_config...
python
def get_custom_color_config_from_egrc(config): """ Get the ColorConfig from the egrc config object. Any colors not defined will be None. """ pound = _get_color_from_config(config, CONFIG_NAMES.pound) heading = _get_color_from_config(config, CONFIG_NAMES.heading) code = _get_color_from_config...
[ "def", "get_custom_color_config_from_egrc", "(", "config", ")", ":", "pound", "=", "_get_color_from_config", "(", "config", ",", "CONFIG_NAMES", ".", "pound", ")", "heading", "=", "_get_color_from_config", "(", "config", ",", "CONFIG_NAMES", ".", "heading", ")", "...
Get the ColorConfig from the egrc config object. Any colors not defined will be None.
[ "Get", "the", "ColorConfig", "from", "the", "egrc", "config", "object", ".", "Any", "colors", "not", "defined", "will", "be", "None", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L393-L428
8,788
srsudar/eg
eg/config.py
_get_color_from_config
def _get_color_from_config(config, option): """ Helper method to uet an option from the COLOR_SECTION of the config. Returns None if the value is not present. If the value is present, it tries to parse the value as a raw string literal, allowing escape sequences in the egrc. """ if not conf...
python
def _get_color_from_config(config, option): """ Helper method to uet an option from the COLOR_SECTION of the config. Returns None if the value is not present. If the value is present, it tries to parse the value as a raw string literal, allowing escape sequences in the egrc. """ if not conf...
[ "def", "_get_color_from_config", "(", "config", ",", "option", ")", ":", "if", "not", "config", ".", "has_option", "(", "COLOR_SECTION", ",", "option", ")", ":", "return", "None", "else", ":", "return", "ast", ".", "literal_eval", "(", "config", ".", "get"...
Helper method to uet an option from the COLOR_SECTION of the config. Returns None if the value is not present. If the value is present, it tries to parse the value as a raw string literal, allowing escape sequences in the egrc.
[ "Helper", "method", "to", "uet", "an", "option", "from", "the", "COLOR_SECTION", "of", "the", "config", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L431-L442
8,789
srsudar/eg
eg/config.py
parse_substitution_from_list
def parse_substitution_from_list(list_rep): """ Parse a substitution from the list representation in the config file. """ # We are expecting [pattern, replacement [, is_multiline]] if type(list_rep) is not list: raise SyntaxError('Substitution must be a list') if len(list_rep) < 2: ...
python
def parse_substitution_from_list(list_rep): """ Parse a substitution from the list representation in the config file. """ # We are expecting [pattern, replacement [, is_multiline]] if type(list_rep) is not list: raise SyntaxError('Substitution must be a list') if len(list_rep) < 2: ...
[ "def", "parse_substitution_from_list", "(", "list_rep", ")", ":", "# We are expecting [pattern, replacement [, is_multiline]]", "if", "type", "(", "list_rep", ")", "is", "not", "list", ":", "raise", "SyntaxError", "(", "'Substitution must be a list'", ")", "if", "len", ...
Parse a substitution from the list representation in the config file.
[ "Parse", "a", "substitution", "from", "the", "list", "representation", "in", "the", "config", "file", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L445-L466
8,790
srsudar/eg
eg/config.py
get_substitutions_from_config
def get_substitutions_from_config(config): """ Return a list of Substitution objects from the config, sorted alphabetically by pattern name. Returns an empty list if no Substitutions are specified. If there are problems parsing the values, a help message will be printed and an error will be thrown. ...
python
def get_substitutions_from_config(config): """ Return a list of Substitution objects from the config, sorted alphabetically by pattern name. Returns an empty list if no Substitutions are specified. If there are problems parsing the values, a help message will be printed and an error will be thrown. ...
[ "def", "get_substitutions_from_config", "(", "config", ")", ":", "result", "=", "[", "]", "pattern_names", "=", "config", ".", "options", "(", "SUBSTITUTION_SECTION", ")", "pattern_names", ".", "sort", "(", ")", "for", "name", "in", "pattern_names", ":", "patt...
Return a list of Substitution objects from the config, sorted alphabetically by pattern name. Returns an empty list if no Substitutions are specified. If there are problems parsing the values, a help message will be printed and an error will be thrown.
[ "Return", "a", "list", "of", "Substitution", "objects", "from", "the", "config", "sorted", "alphabetically", "by", "pattern", "name", ".", "Returns", "an", "empty", "list", "if", "no", "Substitutions", "are", "specified", ".", "If", "there", "are", "problems",...
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L469-L484
8,791
srsudar/eg
eg/config.py
get_default_color_config
def get_default_color_config(): """Get a color config object with all the defaults.""" result = ColorConfig( pound=DEFAULT_COLOR_POUND, heading=DEFAULT_COLOR_HEADING, code=DEFAULT_COLOR_CODE, backticks=DEFAULT_COLOR_BACKTICKS, prompt=DEFAULT_COLOR_PROMPT, pound_re...
python
def get_default_color_config(): """Get a color config object with all the defaults.""" result = ColorConfig( pound=DEFAULT_COLOR_POUND, heading=DEFAULT_COLOR_HEADING, code=DEFAULT_COLOR_CODE, backticks=DEFAULT_COLOR_BACKTICKS, prompt=DEFAULT_COLOR_PROMPT, pound_re...
[ "def", "get_default_color_config", "(", ")", ":", "result", "=", "ColorConfig", "(", "pound", "=", "DEFAULT_COLOR_POUND", ",", "heading", "=", "DEFAULT_COLOR_HEADING", ",", "code", "=", "DEFAULT_COLOR_CODE", ",", "backticks", "=", "DEFAULT_COLOR_BACKTICKS", ",", "pr...
Get a color config object with all the defaults.
[ "Get", "a", "color", "config", "object", "with", "all", "the", "defaults", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L487-L501
8,792
srsudar/eg
eg/config.py
get_empty_config
def get_empty_config(): """ Return an empty Config object with no options set. """ empty_color_config = get_empty_color_config() result = Config( examples_dir=None, custom_dir=None, color_config=empty_color_config, use_color=None, pager_cmd=None, edito...
python
def get_empty_config(): """ Return an empty Config object with no options set. """ empty_color_config = get_empty_color_config() result = Config( examples_dir=None, custom_dir=None, color_config=empty_color_config, use_color=None, pager_cmd=None, edito...
[ "def", "get_empty_config", "(", ")", ":", "empty_color_config", "=", "get_empty_color_config", "(", ")", "result", "=", "Config", "(", "examples_dir", "=", "None", ",", "custom_dir", "=", "None", ",", "color_config", "=", "empty_color_config", ",", "use_color", ...
Return an empty Config object with no options set.
[ "Return", "an", "empty", "Config", "object", "with", "no", "options", "set", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L504-L519
8,793
srsudar/eg
eg/config.py
get_empty_color_config
def get_empty_color_config(): """Return a color_config with all values set to None.""" empty_color_config = ColorConfig( pound=None, heading=None, code=None, backticks=None, prompt=None, pound_reset=None, heading_reset=None, code_reset=None, ...
python
def get_empty_color_config(): """Return a color_config with all values set to None.""" empty_color_config = ColorConfig( pound=None, heading=None, code=None, backticks=None, prompt=None, pound_reset=None, heading_reset=None, code_reset=None, ...
[ "def", "get_empty_color_config", "(", ")", ":", "empty_color_config", "=", "ColorConfig", "(", "pound", "=", "None", ",", "heading", "=", "None", ",", "code", "=", "None", ",", "backticks", "=", "None", ",", "prompt", "=", "None", ",", "pound_reset", "=", ...
Return a color_config with all values set to None.
[ "Return", "a", "color_config", "with", "all", "values", "set", "to", "None", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L522-L536
8,794
srsudar/eg
eg/config.py
merge_color_configs
def merge_color_configs(first, second): """ Merge the color configs. Values in the first will overwrite non-None values in the second. """ # We have to get the desired values first and simultaneously, as nametuple # is immutable. pound = get_priority(first.pound, second.pound, None) hea...
python
def merge_color_configs(first, second): """ Merge the color configs. Values in the first will overwrite non-None values in the second. """ # We have to get the desired values first and simultaneously, as nametuple # is immutable. pound = get_priority(first.pound, second.pound, None) hea...
[ "def", "merge_color_configs", "(", "first", ",", "second", ")", ":", "# We have to get the desired values first and simultaneously, as nametuple", "# is immutable.", "pound", "=", "get_priority", "(", "first", ".", "pound", ",", "second", ".", "pound", ",", "None", ")",...
Merge the color configs. Values in the first will overwrite non-None values in the second.
[ "Merge", "the", "color", "configs", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L539-L591
8,795
srsudar/eg
eg/substitute.py
Substitution.apply_and_get_result
def apply_and_get_result(self, string): """ Perform the substitution represented by this object on string and return the result. """ if self.is_multiline: compiled_pattern = re.compile(self.pattern, re.MULTILINE) else: compiled_pattern = re.compile...
python
def apply_and_get_result(self, string): """ Perform the substitution represented by this object on string and return the result. """ if self.is_multiline: compiled_pattern = re.compile(self.pattern, re.MULTILINE) else: compiled_pattern = re.compile...
[ "def", "apply_and_get_result", "(", "self", ",", "string", ")", ":", "if", "self", ".", "is_multiline", ":", "compiled_pattern", "=", "re", ".", "compile", "(", "self", ".", "pattern", ",", "re", ".", "MULTILINE", ")", "else", ":", "compiled_pattern", "=",...
Perform the substitution represented by this object on string and return the result.
[ "Perform", "the", "substitution", "represented", "by", "this", "object", "on", "string", "and", "return", "the", "result", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/substitute.py#L23-L34
8,796
srsudar/eg
eg/color.py
EgColorizer.colorize_text
def colorize_text(self, text): """Colorize the text.""" # As originally implemented, this method acts upon all the contents of # the file as a single string using the MULTILINE option of the re # package. I believe this was ostensibly for performance reasons, but # it has a few s...
python
def colorize_text(self, text): """Colorize the text.""" # As originally implemented, this method acts upon all the contents of # the file as a single string using the MULTILINE option of the re # package. I believe this was ostensibly for performance reasons, but # it has a few s...
[ "def", "colorize_text", "(", "self", ",", "text", ")", ":", "# As originally implemented, this method acts upon all the contents of", "# the file as a single string using the MULTILINE option of the re", "# package. I believe this was ostensibly for performance reasons, but", "# it has a few s...
Colorize the text.
[ "Colorize", "the", "text", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/color.py#L67-L85
8,797
srsudar/eg
eg/util.py
_recursive_get_all_file_names
def _recursive_get_all_file_names(dir): """ Get all the file names in the directory. Gets all the top level file names only, not the full path. dir: a directory or string, as to hand to os.walk(). If None, returns empty list. """ if not dir: return [] result = [] for ba...
python
def _recursive_get_all_file_names(dir): """ Get all the file names in the directory. Gets all the top level file names only, not the full path. dir: a directory or string, as to hand to os.walk(). If None, returns empty list. """ if not dir: return [] result = [] for ba...
[ "def", "_recursive_get_all_file_names", "(", "dir", ")", ":", "if", "not", "dir", ":", "return", "[", "]", "result", "=", "[", "]", "for", "basedir", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "dir", ")", ":", "result", ".", "extend", ...
Get all the file names in the directory. Gets all the top level file names only, not the full path. dir: a directory or string, as to hand to os.walk(). If None, returns empty list.
[ "Get", "all", "the", "file", "names", "in", "the", "directory", ".", "Gets", "all", "the", "top", "level", "file", "names", "only", "not", "the", "full", "path", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L49-L64
8,798
srsudar/eg
eg/util.py
edit_custom_examples
def edit_custom_examples(program, config): """ Edit custom examples for the given program, creating the file if it does not exist. """ if (not config.custom_dir) or (not os.path.exists(config.custom_dir)): _inform_cannot_edit_no_custom_dir() return # resolve aliases resolved...
python
def edit_custom_examples(program, config): """ Edit custom examples for the given program, creating the file if it does not exist. """ if (not config.custom_dir) or (not os.path.exists(config.custom_dir)): _inform_cannot_edit_no_custom_dir() return # resolve aliases resolved...
[ "def", "edit_custom_examples", "(", "program", ",", "config", ")", ":", "if", "(", "not", "config", ".", "custom_dir", ")", "or", "(", "not", "os", ".", "path", ".", "exists", "(", "config", ".", "custom_dir", ")", ")", ":", "_inform_cannot_edit_no_custom_...
Edit custom examples for the given program, creating the file if it does not exist.
[ "Edit", "custom", "examples", "for", "the", "given", "program", "creating", "the", "file", "if", "it", "does", "not", "exist", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L67-L90
8,799
srsudar/eg
eg/util.py
get_file_paths_for_program
def get_file_paths_for_program(program, dir_to_search): """ Return an array of full paths matching the given program. If no directory is present, returns an empty list. Path is not guaranteed to exist. Just says where it should be if it existed. Paths must be fully expanded before being passed in (...
python
def get_file_paths_for_program(program, dir_to_search): """ Return an array of full paths matching the given program. If no directory is present, returns an empty list. Path is not guaranteed to exist. Just says where it should be if it existed. Paths must be fully expanded before being passed in (...
[ "def", "get_file_paths_for_program", "(", "program", ",", "dir_to_search", ")", ":", "if", "dir_to_search", "is", "None", ":", "return", "[", "]", "else", ":", "wanted_file_name", "=", "program", "+", "EXAMPLE_FILE_SUFFIX", "result", "=", "[", "]", "for", "bas...
Return an array of full paths matching the given program. If no directory is present, returns an empty list. Path is not guaranteed to exist. Just says where it should be if it existed. Paths must be fully expanded before being passed in (i.e. no ~ or variables).
[ "Return", "an", "array", "of", "full", "paths", "matching", "the", "given", "program", ".", "If", "no", "directory", "is", "present", "returns", "an", "empty", "list", "." ]
96142a74f4416b4a7000c85032c070df713b849e
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L131-L150