Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
IcoFile.__init__
(self, buf)
Parse image from file-like object containing ico file data
Parse image from file-like object containing ico file data
def __init__(self, buf): """ Parse image from file-like object containing ico file data """ # check magic s = buf.read(6) if not _accept(s): raise SyntaxError("not an ICO file") self.buf = buf self.entry = [] # Number of items in fil...
[ "def", "__init__", "(", "self", ",", "buf", ")", ":", "# check magic", "s", "=", "buf", ".", "read", "(", "6", ")", "if", "not", "_accept", "(", "s", ")", ":", "raise", "SyntaxError", "(", "\"not an ICO file\"", ")", "self", ".", "buf", "=", "buf", ...
[ 86, 4 ]
[ 142, 28 ]
python
en
['en', 'error', 'th']
False
IcoFile.sizes
(self)
Get a list of all available icon sizes and color depths.
Get a list of all available icon sizes and color depths.
def sizes(self): """ Get a list of all available icon sizes and color depths. """ return {(h["width"], h["height"]) for h in self.entry}
[ "def", "sizes", "(", "self", ")", ":", "return", "{", "(", "h", "[", "\"width\"", "]", ",", "h", "[", "\"height\"", "]", ")", "for", "h", "in", "self", ".", "entry", "}" ]
[ 144, 4 ]
[ 148, 62 ]
python
en
['en', 'error', 'th']
False
IcoFile.getimage
(self, size, bpp=False)
Get an image from the icon
Get an image from the icon
def getimage(self, size, bpp=False): """ Get an image from the icon """ return self.frame(self.getentryindex(size, bpp))
[ "def", "getimage", "(", "self", ",", "size", ",", "bpp", "=", "False", ")", ":", "return", "self", ".", "frame", "(", "self", ".", "getentryindex", "(", "size", ",", "bpp", ")", ")" ]
[ 156, 4 ]
[ 160, 56 ]
python
en
['en', 'error', 'th']
False
IcoFile.frame
(self, idx)
Get an image from frame idx
Get an image from frame idx
def frame(self, idx): """ Get an image from frame idx """ header = self.entry[idx] self.buf.seek(header["offset"]) data = self.buf.read(8) self.buf.seek(header["offset"]) if data[:8] == PngImagePlugin._MAGIC: # png frame im = Png...
[ "def", "frame", "(", "self", ",", "idx", ")", ":", "header", "=", "self", ".", "entry", "[", "idx", "]", "self", ".", "buf", ".", "seek", "(", "header", "[", "\"offset\"", "]", ")", "data", "=", "self", ".", "buf", ".", "read", "(", "8", ")", ...
[ 162, 4 ]
[ 244, 17 ]
python
en
['en', 'error', 'th']
False
Template.context
(self)
Context for template.
Context for template.
def context(self): """Context for template.""" raise NotImplementedError
[ "def", "context", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 38, 4 ]
[ 40, 33 ]
python
en
['en', 'en', 'en']
True
Template.iter_clean
(self, data=None)
Yields cleaned data. Args: data (str, optional): Alternative data to clean. Defaults to None. If none, uses template render.
Yields cleaned data.
def iter_clean(self, data=None): """Yields cleaned data. Args: data (str, optional): Alternative data to clean. Defaults to None. If none, uses template render. """ render = data or self.template.render(self.context) for line in render.splitlines(Tru...
[ "def", "iter_clean", "(", "self", ",", "data", "=", "None", ")", ":", "render", "=", "data", "or", "self", ".", "template", ".", "render", "(", "self", ".", "context", ")", "for", "line", "in", "render", ".", "splitlines", "(", "True", ")", ":", "_...
[ 42, 4 ]
[ 54, 26 ]
python
en
['en', 'en', 'en']
True
Template.run_checks
(self)
Runs all template checks. Returns: bool: True if all checks passed
Runs all template checks.
def run_checks(self): """Runs all template checks. Returns: bool: True if all checks passed """ if not self.CHECKS: return True results = [not ck() for ck in self.CHECKS] return any(results)
[ "def", "run_checks", "(", "self", ")", ":", "if", "not", "self", ".", "CHECKS", ":", "return", "True", "results", "=", "[", "not", "ck", "(", ")", "for", "ck", "in", "self", ".", "CHECKS", "]", "return", "any", "(", "results", ")" ]
[ 56, 4 ]
[ 66, 27 ]
python
en
['en', 'gd', 'en']
True
Template.update
(self, root)
Update Template File. Args: root (str): Path to project root Raises: NotImplementedError: Raised if Subclass has not Implemented Update Returns: func: Template Update Func
Update Template File.
def update(self, root): """Update Template File. Args: root (str): Path to project root Raises: NotImplementedError: Raised if Subclass has not Implemented Update Returns: func: Template Update Func """ update_func = getattr(self, "...
[ "def", "update", "(", "self", ",", "root", ")", ":", "update_func", "=", "getattr", "(", "self", ",", "\"update_method\"", ",", "None", ")", "update_kwargs", "=", "getattr", "(", "self", ",", "\"update_kwargs\"", ",", "{", "}", ")", "if", "not", "update_...
[ 68, 4 ]
[ 86, 49 ]
python
en
['en', 'co', 'en']
True
Template.update_as_json
(self, path)
Update template file as JSON. Args: path (str): File path to update
Update template file as JSON.
def update_as_json(self, path): """Update template file as JSON. Args: path (str): File path to update """ render = json.loads("".join(self.iter_clean())) data = json.loads("".join(self.iter_clean(path.read_text()))) data.update(render) with path.ope...
[ "def", "update_as_json", "(", "self", ",", "path", ")", ":", "render", "=", "json", ".", "loads", "(", "\"\"", ".", "join", "(", "self", ".", "iter_clean", "(", ")", ")", ")", "data", "=", "json", ".", "loads", "(", "\"\"", ".", "join", "(", "sel...
[ 88, 4 ]
[ 99, 40 ]
python
en
['en', 'en', 'en']
True
Template.update_as_text
(self, path, by_contains=None)
Update template file as text. Args: path (str): file path to update. by_contains ([str], optional): Update lines that contain a string. Defaults to None.
Update template file as text.
def update_as_text(self, path, by_contains=None): """Update template file as text. Args: path (str): file path to update. by_contains ([str], optional): Update lines that contain a string. Defaults to None. """ r_lines = list(self.iter_clean()) ...
[ "def", "update_as_text", "(", "self", ",", "path", ",", "by_contains", "=", "None", ")", ":", "r_lines", "=", "list", "(", "self", ".", "iter_clean", "(", ")", ")", "upd_lines", "=", "[", "]", "if", "by_contains", ":", "upd_lines", "=", "[", "r_lines",...
[ 101, 4 ]
[ 121, 30 ]
python
en
['en', 'en', 'en']
True
Template.render_stream
(self)
Returns template stream from context.
Returns template stream from context.
def render_stream(self): """Returns template stream from context.""" stream = self.template.stream(self.context) return stream
[ "def", "render_stream", "(", "self", ")", ":", "stream", "=", "self", ".", "template", ".", "stream", "(", "self", ".", "context", ")", "return", "stream" ]
[ 123, 4 ]
[ 126, 21 ]
python
en
['en', 'en', 'en']
True
Template.iter_relative_paths
(self, paths: List[Path], strict: bool = False)
Iterate over a list of paths relative to project root. Args: paths: List of paths to make relative. strict: Raises ValueError if True and path cannot be made relative. Defaults to False. Raises: ValueError: Path could not be made relative and `strict...
Iterate over a list of paths relative to project root.
def iter_relative_paths(self, paths: List[Path], strict: bool = False) -> Iterator[Path]: """Iterate over a list of paths relative to project root. Args: paths: List of paths to make relative. strict: Raises ValueError if True and path cannot be made relative. De...
[ "def", "iter_relative_paths", "(", "self", ",", "paths", ":", "List", "[", "Path", "]", ",", "strict", ":", "bool", "=", "False", ")", "->", "Iterator", "[", "Path", "]", ":", "for", "p", "in", "paths", ":", "path", "=", "p", "if", "not", "p", "....
[ 128, 4 ]
[ 150, 26 ]
python
en
['en', 'en', 'en']
True
GenericTemplate.context
(self)
Empty Context.
Empty Context.
def context(self): """Empty Context.""" return {}
[ "def", "context", "(", "self", ")", ":", "return", "{", "}" ]
[ 165, 4 ]
[ 167, 17 ]
python
en
['en', 'sr', 'en']
False
CodeTemplate.context
(self)
VScode Config Context.
VScode Config Context.
def context(self): """VScode Config Context.""" paths = self.paths if self.datadir: paths = list(self.iter_relative_paths(self.paths, strict=True)) if self.local_paths: paths.extend(self.iter_relative_paths(self.local_paths)) stub_paths = json.dumps([str(s...
[ "def", "context", "(", "self", ")", ":", "paths", "=", "self", ".", "paths", "if", "self", ".", "datadir", ":", "paths", "=", "list", "(", "self", ".", "iter_relative_paths", "(", "self", ".", "paths", ",", "strict", "=", "True", ")", ")", "if", "s...
[ 181, 4 ]
[ 193, 18 ]
python
gl
['nl', 'gl', 'it']
False
PylintTemplate.context
(self)
Pylint Config Context.
Pylint Config Context.
def context(self): """Pylint Config Context.""" paths = self.paths if self.datadir: paths = list(self.iter_relative_paths(self.paths, strict=True)) if self.local_paths: paths.extend(self.iter_relative_paths(self.local_paths)) ctx = {"stubs": self.stubs or ...
[ "def", "context", "(", "self", ")", ":", "paths", "=", "self", ".", "paths", "if", "self", ".", "datadir", ":", "paths", "=", "list", "(", "self", ".", "iter_relative_paths", "(", "self", ".", "paths", ",", "strict", "=", "True", ")", ")", "if", "s...
[ 207, 4 ]
[ 215, 18 ]
python
ca
['de', 'ca', 'it']
False
TemplateProvider.__init__
(self, templates, log=None, **kwargs)
Template Factory. Args: templates ([str]): List of Templates to use log (callable, optional): Log instance to use. Defaults to None. If none, creates a new one. run_checks (bool, optional): Whether to run template checks. Defaults to True. ...
Template Factory.
def __init__(self, templates, log=None, **kwargs): """Template Factory. Args: templates ([str]): List of Templates to use log (callable, optional): Log instance to use. Defaults to None. If none, creates a new one. run_checks (bool, optional): Whether...
[ "def", "__init__", "(", "self", ",", "templates", ",", "log", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "run_checks", "=", "kwargs", ".", "get", "(", "\"run_checks\"", ",", "True", ")", "self", ".", "template_names", "=", "set", "(...
[ 243, 4 ]
[ 264, 86 ]
python
en
['en', 'en', 'en']
False
TemplateProvider.get
(self, name, *args, **kwargs)
Retrieve appropriate Template instance by name. Args: name (str): Name of template Returns: Template: Template instance
Retrieve appropriate Template instance by name.
def get(self, name, *args, **kwargs): """Retrieve appropriate Template instance by name. Args: name (str): Name of template Returns: Template: Template instance """ temp_def = self.files.get(name) file_attr = getattr(temp_def, "FILENAME", None) ...
[ "def", "get", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "temp_def", "=", "self", ".", "files", ".", "get", "(", "name", ")", "file_attr", "=", "getattr", "(", "temp_def", ",", "\"FILENAME\"", ",", "None", ")", ...
[ 266, 4 ]
[ 283, 23 ]
python
en
['en', 'en', 'en']
True
TemplateProvider.render_to
(self, name, parent_dir, *args, **kwargs)
Renders Template to a file under parent directory. Args: name (str): Name of template parent_dir (str): Path to root dir
Renders Template to a file under parent directory.
def render_to(self, name, parent_dir, *args, **kwargs): """Renders Template to a file under parent directory. Args: name (str): Name of template parent_dir (str): Path to root dir """ template = self.get(name, **kwargs) self.log.debug(f"Loaded: {str(temp...
[ "def", "render_to", "(", "self", ",", "name", ",", "parent_dir", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "template", "=", "self", ".", "get", "(", "name", ",", "*", "*", "kwargs", ")", "self", ".", "log", ".", "debug", "(", "f\"Loade...
[ 285, 4 ]
[ 310, 66 ]
python
en
['en', 'en', 'en']
True
TemplateProvider.update
(self, name, root_dir, **kwargs)
Update existing Template. Args: name (str): Template name root_dir (str): Path to project root Returns: Template: Updated Template Instance
Update existing Template.
def update(self, name, root_dir, **kwargs): """Update existing Template. Args: name (str): Template name root_dir (str): Path to project root Returns: Template: Updated Template Instance """ template = self.get(name, **kwargs) self.l...
[ "def", "update", "(", "self", ",", "name", ",", "root_dir", ",", "*", "*", "kwargs", ")", ":", "template", "=", "self", ".", "get", "(", "name", ",", "*", "*", "kwargs", ")", "self", ".", "log", ".", "debug", "(", "f\"Loaded: {str(template)}\"", ")",...
[ 312, 4 ]
[ 331, 23 ]
python
en
['es', 'en', 'en']
True
TemplateProvider.templates
(self)
returns all template names.
returns all template names.
def templates(self): """returns all template names.""" return self.files.keys()
[ "def", "templates", "(", "self", ")", ":", "return", "self", ".", "files", ".", "keys", "(", ")" ]
[ 334, 4 ]
[ 336, 32 ]
python
en
['en', 'en', 'en']
True
test_image_transcoding
(space_resource, format, image_type)
Test that images get transcoded into JPEG or PNG if they're not JPEG/PNG
Test that images get transcoded into JPEG or PNG if they're not JPEG/PNG
def test_image_transcoding(space_resource, format, image_type): """ Test that images get transcoded into JPEG or PNG if they're not JPEG/PNG """ data = get_test_image_data(format=format) ri = ResourceImage( resource=space_resource, sort_order=8, type=image_type, image...
[ "def", "test_image_transcoding", "(", "space_resource", ",", "format", ",", "image_type", ")", ":", "data", "=", "get_test_image_data", "(", "format", "=", "format", ")", "ri", "=", "ResourceImage", "(", "resource", "=", "space_resource", ",", "sort_order", "=",...
[ 34, 0 ]
[ 48, 57 ]
python
en
['en', 'error', 'th']
False
test_image_transcoding_bypass
(space_resource, format)
Test that JPEGs and PNGs bypass transcoding
Test that JPEGs and PNGs bypass transcoding
def test_image_transcoding_bypass(space_resource, format): """ Test that JPEGs and PNGs bypass transcoding """ data = get_test_image_data(format=format) ri = ResourceImage( resource=space_resource, sort_order=8, type="main", image=ContentFile(data, name="nice.%s" % fo...
[ "def", "test_image_transcoding_bypass", "(", "space_resource", ",", "format", ")", ":", "data", "=", "get_test_image_data", "(", "format", "=", "format", ")", "ri", "=", "ResourceImage", "(", "resource", "=", "space_resource", ",", "sort_order", "=", "8", ",", ...
[ 53, 0 ]
[ 68, 34 ]
python
en
['en', 'error', 'th']
False
autocontrast
(image, cutoff=0, ignore=None)
Maximize (normalize) image contrast. This function calculates a histogram of the input image, removes **cutoff** percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel becomes black (0), and the lightest becomes white (255). :param image: ...
Maximize (normalize) image contrast. This function calculates a histogram of the input image, removes **cutoff** percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel becomes black (0), and the lightest becomes white (255).
def autocontrast(image, cutoff=0, ignore=None): """ Maximize (normalize) image contrast. This function calculates a histogram of the input image, removes **cutoff** percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel becomes black (0), and th...
[ "def", "autocontrast", "(", "image", ",", "cutoff", "=", "0", ",", "ignore", "=", "None", ")", ":", "histogram", "=", "image", ".", "histogram", "(", ")", "lut", "=", "[", "]", "for", "layer", "in", "range", "(", "0", ",", "len", "(", "histogram", ...
[ 63, 0 ]
[ 136, 27 ]
python
en
['en', 'error', 'th']
False
colorize
(image, black, white, mid=None, blackpoint=0, whitepoint=255, midpoint=127)
Colorize grayscale image. This function calculates a color wedge which maps all black pixels in the source image to the first color and all white pixels to the second color. If **mid** is specified, it uses three-color mapping. The **black** and **white** arguments should be RGB tuples or color nam...
Colorize grayscale image. This function calculates a color wedge which maps all black pixels in the source image to the first color and all white pixels to the second color. If **mid** is specified, it uses three-color mapping. The **black** and **white** arguments should be RGB tuples or color nam...
def colorize(image, black, white, mid=None, blackpoint=0, whitepoint=255, midpoint=127): """ Colorize grayscale image. This function calculates a color wedge which maps all black pixels in the source image to the first color and all white pixels to the second color. If **mid** is specified, it uses ...
[ "def", "colorize", "(", "image", ",", "black", ",", "white", ",", "mid", "=", "None", ",", "blackpoint", "=", "0", ",", "whitepoint", "=", "255", ",", "midpoint", "=", "127", ")", ":", "# Initial asserts", "assert", "image", ".", "mode", "==", "\"L\"",...
[ 139, 0 ]
[ 220, 42 ]
python
en
['en', 'error', 'th']
False
pad
(image, size, method=Image.BICUBIC, color=None, centering=(0.5, 0.5))
Returns a sized and padded version of the image, expanded to fill the requested aspect ratio and size. :param image: The image to size and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :param method: What resampling method to use. Defaul...
Returns a sized and padded version of the image, expanded to fill the requested aspect ratio and size.
def pad(image, size, method=Image.BICUBIC, color=None, centering=(0.5, 0.5)): """ Returns a sized and padded version of the image, expanded to fill the requested aspect ratio and size. :param image: The image to size and crop. :param size: The requested output size in pixels, given as a ...
[ "def", "pad", "(", "image", ",", "size", ",", "method", "=", "Image", ".", "BICUBIC", ",", "color", "=", "None", ",", "centering", "=", "(", "0.5", ",", "0.5", ")", ")", ":", "im_ratio", "=", "image", ".", "width", "/", "image", ".", "height", "d...
[ 223, 0 ]
[ 265, 14 ]
python
en
['en', 'error', 'th']
False
crop
(image, border=0)
Remove border from image. The same amount of pixels are removed from all four sides. This function works on all image modes. .. seealso:: :py:meth:`~PIL.Image.Image.crop` :param image: The image to crop. :param border: The number of pixels to remove. :return: An image.
Remove border from image. The same amount of pixels are removed from all four sides. This function works on all image modes.
def crop(image, border=0): """ Remove border from image. The same amount of pixels are removed from all four sides. This function works on all image modes. .. seealso:: :py:meth:`~PIL.Image.Image.crop` :param image: The image to crop. :param border: The number of pixels to remove. :retur...
[ "def", "crop", "(", "image", ",", "border", "=", "0", ")", ":", "left", ",", "top", ",", "right", ",", "bottom", "=", "_border", "(", "border", ")", "return", "image", ".", "crop", "(", "(", "left", ",", "top", ",", "image", ".", "size", "[", "...
[ 268, 0 ]
[ 280, 81 ]
python
en
['en', 'error', 'th']
False
scale
(image, factor, resample=Image.BICUBIC)
Returns a rescaled image by a specific factor given in parameter. A factor greater than 1 expands the image, between 0 and 1 contracts the image. :param image: The image to rescale. :param factor: The expansion factor, as a float. :param resample: What resampling method to use. Default is ...
Returns a rescaled image by a specific factor given in parameter. A factor greater than 1 expands the image, between 0 and 1 contracts the image.
def scale(image, factor, resample=Image.BICUBIC): """ Returns a rescaled image by a specific factor given in parameter. A factor greater than 1 expands the image, between 0 and 1 contracts the image. :param image: The image to rescale. :param factor: The expansion factor, as a float. :param...
[ "def", "scale", "(", "image", ",", "factor", ",", "resample", "=", "Image", ".", "BICUBIC", ")", ":", "if", "factor", "==", "1", ":", "return", "image", ".", "copy", "(", ")", "elif", "factor", "<=", "0", ":", "raise", "ValueError", "(", "\"the facto...
[ 283, 0 ]
[ 301, 43 ]
python
en
['en', 'error', 'th']
False
deform
(image, deformer, resample=Image.BILINEAR)
Deform the image. :param image: The image to deform. :param deformer: A deformer object. Any object that implements a **getmesh** method can be used. :param resample: An optional resampling filter. Same values possible as in the PIL.Image.transform function. :return: An...
Deform the image.
def deform(image, deformer, resample=Image.BILINEAR): """ Deform the image. :param image: The image to deform. :param deformer: A deformer object. Any object that implements a **getmesh** method can be used. :param resample: An optional resampling filter. Same values possible a...
[ "def", "deform", "(", "image", ",", "deformer", ",", "resample", "=", "Image", ".", "BILINEAR", ")", ":", "return", "image", ".", "transform", "(", "image", ".", "size", ",", "Image", ".", "MESH", ",", "deformer", ".", "getmesh", "(", "image", ")", "...
[ 304, 0 ]
[ 315, 85 ]
python
en
['en', 'error', 'th']
False
equalize
(image, mask=None)
Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image. :param image: The image to equalize. :param mask: An optional mask. If given, only the pixels selected by ...
Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image.
def equalize(image, mask=None): """ Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image. :param image: The image to equalize. :param mask: An optional mask. If given, only...
[ "def", "equalize", "(", "image", ",", "mask", "=", "None", ")", ":", "if", "image", ".", "mode", "==", "\"P\"", ":", "image", "=", "image", ".", "convert", "(", "\"RGB\"", ")", "h", "=", "image", ".", "histogram", "(", "mask", ")", "lut", "=", "[...
[ 318, 0 ]
[ 346, 27 ]
python
en
['en', 'error', 'th']
False
expand
(image, border=0, fill=0)
Add border to the image :param image: The image to expand. :param border: Border width, in pixels. :param fill: Pixel fill value (a color value). Default is 0 (black). :return: An image.
Add border to the image
def expand(image, border=0, fill=0): """ Add border to the image :param image: The image to expand. :param border: Border width, in pixels. :param fill: Pixel fill value (a color value). Default is 0 (black). :return: An image. """ left, top, right, bottom = _border(border) width =...
[ "def", "expand", "(", "image", ",", "border", "=", "0", ",", "fill", "=", "0", ")", ":", "left", ",", "top", ",", "right", ",", "bottom", "=", "_border", "(", "border", ")", "width", "=", "left", "+", "image", ".", "size", "[", "0", "]", "+", ...
[ 349, 0 ]
[ 363, 14 ]
python
en
['en', 'error', 'th']
False
fit
(image, size, method=Image.BICUBIC, bleed=0.0, centering=(0.5, 0.5))
Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size. This function was contributed by Kevin Cazabon. :param image: The image to size and crop. :param size: The requested output size in pixels, given as a (width, height) tuple. :par...
Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size.
def fit(image, size, method=Image.BICUBIC, bleed=0.0, centering=(0.5, 0.5)): """ Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size. This function was contributed by Kevin Cazabon. :param image: The image to size and crop. :param size: The requeste...
[ "def", "fit", "(", "image", ",", "size", ",", "method", "=", "Image", ".", "BICUBIC", ",", "bleed", "=", "0.0", ",", "centering", "=", "(", "0.5", ",", "0.5", ")", ")", ":", "# by Kevin Cazabon, Feb 17/2000", "# kevin@cazabon.com", "# http://www.cazabon.com", ...
[ 366, 0 ]
[ 448, 47 ]
python
en
['en', 'error', 'th']
False
flip
(image)
Flip the image vertically (top to bottom). :param image: The image to flip. :return: An image.
Flip the image vertically (top to bottom).
def flip(image): """ Flip the image vertically (top to bottom). :param image: The image to flip. :return: An image. """ return image.transpose(Image.FLIP_TOP_BOTTOM)
[ "def", "flip", "(", "image", ")", ":", "return", "image", ".", "transpose", "(", "Image", ".", "FLIP_TOP_BOTTOM", ")" ]
[ 451, 0 ]
[ 458, 49 ]
python
en
['en', 'error', 'th']
False
grayscale
(image)
Convert the image to grayscale. :param image: The image to convert. :return: An image.
Convert the image to grayscale.
def grayscale(image): """ Convert the image to grayscale. :param image: The image to convert. :return: An image. """ return image.convert("L")
[ "def", "grayscale", "(", "image", ")", ":", "return", "image", ".", "convert", "(", "\"L\"", ")" ]
[ 461, 0 ]
[ 468, 29 ]
python
en
['en', 'error', 'th']
False
invert
(image)
Invert (negate) the image. :param image: The image to invert. :return: An image.
Invert (negate) the image.
def invert(image): """ Invert (negate) the image. :param image: The image to invert. :return: An image. """ lut = [] for i in range(256): lut.append(255 - i) return _lut(image, lut)
[ "def", "invert", "(", "image", ")", ":", "lut", "=", "[", "]", "for", "i", "in", "range", "(", "256", ")", ":", "lut", ".", "append", "(", "255", "-", "i", ")", "return", "_lut", "(", "image", ",", "lut", ")" ]
[ 471, 0 ]
[ 481, 27 ]
python
en
['en', 'error', 'th']
False
mirror
(image)
Flip image horizontally (left to right). :param image: The image to mirror. :return: An image.
Flip image horizontally (left to right).
def mirror(image): """ Flip image horizontally (left to right). :param image: The image to mirror. :return: An image. """ return image.transpose(Image.FLIP_LEFT_RIGHT)
[ "def", "mirror", "(", "image", ")", ":", "return", "image", ".", "transpose", "(", "Image", ".", "FLIP_LEFT_RIGHT", ")" ]
[ 484, 0 ]
[ 491, 49 ]
python
en
['en', 'error', 'th']
False
posterize
(image, bits)
Reduce the number of bits for each color channel. :param image: The image to posterize. :param bits: The number of bits to keep for each channel (1-8). :return: An image.
Reduce the number of bits for each color channel.
def posterize(image, bits): """ Reduce the number of bits for each color channel. :param image: The image to posterize. :param bits: The number of bits to keep for each channel (1-8). :return: An image. """ lut = [] mask = ~(2 ** (8 - bits) - 1) for i in range(256): lut.appe...
[ "def", "posterize", "(", "image", ",", "bits", ")", ":", "lut", "=", "[", "]", "mask", "=", "~", "(", "2", "**", "(", "8", "-", "bits", ")", "-", "1", ")", "for", "i", "in", "range", "(", "256", ")", ":", "lut", ".", "append", "(", "i", "...
[ 494, 0 ]
[ 506, 27 ]
python
en
['en', 'error', 'th']
False
solarize
(image, threshold=128)
Invert all pixel values above a threshold. :param image: The image to solarize. :param threshold: All pixels above this greyscale level are inverted. :return: An image.
Invert all pixel values above a threshold.
def solarize(image, threshold=128): """ Invert all pixel values above a threshold. :param image: The image to solarize. :param threshold: All pixels above this greyscale level are inverted. :return: An image. """ lut = [] for i in range(256): if i < threshold: lut.ap...
[ "def", "solarize", "(", "image", ",", "threshold", "=", "128", ")", ":", "lut", "=", "[", "]", "for", "i", "in", "range", "(", "256", ")", ":", "if", "i", "<", "threshold", ":", "lut", ".", "append", "(", "i", ")", "else", ":", "lut", ".", "a...
[ 509, 0 ]
[ 523, 27 ]
python
en
['en', 'error', 'th']
False
exif_transpose
(image)
If an image has an EXIF Orientation tag, return a new image that is transposed accordingly. Otherwise, return a copy of the image. :param image: The image to transpose. :return: An image.
If an image has an EXIF Orientation tag, return a new image that is transposed accordingly. Otherwise, return a copy of the image.
def exif_transpose(image): """ If an image has an EXIF Orientation tag, return a new image that is transposed accordingly. Otherwise, return a copy of the image. :param image: The image to transpose. :return: An image. """ exif = image.getexif() orientation = exif.get(0x0112) method...
[ "def", "exif_transpose", "(", "image", ")", ":", "exif", "=", "image", ".", "getexif", "(", ")", "orientation", "=", "exif", ".", "get", "(", "0x0112", ")", "method", "=", "{", "2", ":", "Image", ".", "FLIP_LEFT_RIGHT", ",", "3", ":", "Image", ".", ...
[ 526, 0 ]
[ 550, 23 ]
python
en
['en', 'error', 'th']
False
Client.flag_community
(self, comId: str, reason: str, flagType: int)
Flag a Community. **Parameters** - **comId** : Id of the community. - **reason** : Reason of the flag. - **flagType** : Type of flag. **Returns** - **Success** : :meth:`Json Object <samino.lib.objects.Json>` - **Fail** : :meth:`Exce...
Flag a Community.
def flag_community(self, comId: str, reason: str, flagType: int): # Changed by SirLez """ Flag a Community. **Parameters** - **comId** : Id of the community. - **reason** : Reason of the flag. - **flagType** : Type of flag. **Returns** -...
[ "def", "flag_community", "(", "self", ",", "comId", ":", "str", ",", "reason", ":", "str", ",", "flagType", ":", "int", ")", ":", "# Changed by SirLez", "data", "=", "json", ".", "dumps", "(", "{", "\"objectId\"", ":", "comId", ",", "\"objectType\"", ":"...
[ 241, 4 ]
[ 265, 31 ]
python
en
['en', 'error', 'th']
False
Client.get_from_id
(self, id: str, comId: str = None, objectType: int = 2)
Get Link from Id. **Parameters** - **comId** : Id of the community. - **objectType** : Object type of the id. - **id** : The id. **Returns** - **Success** : :meth:`Json Object <samino.lib.objects.Json>` - **Fail** : :meth:`Exception...
Get Link from Id.
def get_from_id(self, id: str, comId: str = None, objectType: int = 2): # never tried """ Get Link from Id. **Parameters** - **comId** : Id of the community. - **objectType** : Object type of the id. - **id** : The id. **Returns** - **Su...
[ "def", "get_from_id", "(", "self", ",", "id", ":", "str", ",", "comId", ":", "str", "=", "None", ",", "objectType", ":", "int", "=", "2", ")", ":", "# never tried", "data", "=", "json", ".", "dumps", "(", "{", "\"objectId\"", ":", "id", ",", "\"tar...
[ 517, 4 ]
[ 545, 73 ]
python
en
['en', 'error', 'th']
False
get_pointer_arr
(n)
Gets a ctypes pointer array (of length `n`) for GEOSGeom_t opaque pointer.
Gets a ctypes pointer array (of length `n`) for GEOSGeom_t opaque pointer.
def get_pointer_arr(n): "Gets a ctypes pointer array (of length `n`) for GEOSGeom_t opaque pointer." GeomArr = GEOM_PTR * n return GeomArr()
[ "def", "get_pointer_arr", "(", "n", ")", ":", "GeomArr", "=", "GEOM_PTR", "*", "n", "return", "GeomArr", "(", ")" ]
[ 117, 0 ]
[ 120, 20 ]
python
en
['en', 'en', 'en']
True
geos_version_info
()
Returns a dictionary containing the various version metadata parsed from the GEOS version string, including the version number, whether the version is a release candidate (and what number release candidate), and the C API version.
Returns a dictionary containing the various version metadata parsed from the GEOS version string, including the version number, whether the version is a release candidate (and what number release candidate), and the C API version.
def geos_version_info(): """ Returns a dictionary containing the various version metadata parsed from the GEOS version string, including the version number, whether the version is a release candidate (and what number release candidate), and the C API version. """ ver = geos_version().decode(...
[ "def", "geos_version_info", "(", ")", ":", "ver", "=", "geos_version", "(", ")", ".", "decode", "(", ")", "m", "=", "version_regex", ".", "match", "(", "ver", ")", "if", "not", "m", ":", "raise", "GEOSException", "(", "'Could not parse version info string \"...
[ 136, 0 ]
[ 148, 86 ]
python
en
['en', 'error', 'th']
False
check_resolver
(resolver)
Recursively check the resolver.
Recursively check the resolver.
def check_resolver(resolver): """ Recursively check the resolver. """ check_method = getattr(resolver, 'check', None) if check_method is not None: return check_method() elif not hasattr(resolver, 'resolve'): return get_warning_for_invalid_pattern(resolver) else: retur...
[ "def", "check_resolver", "(", "resolver", ")", ":", "check_method", "=", "getattr", "(", "resolver", ",", "'check'", ",", "None", ")", "if", "check_method", "is", "not", "None", ":", "return", "check_method", "(", ")", "elif", "not", "hasattr", "(", "resol...
[ 16, 0 ]
[ 26, 17 ]
python
en
['en', 'error', 'th']
False
check_url_namespaces_unique
(app_configs, **kwargs)
Warn if URL namespaces used in applications aren't unique.
Warn if URL namespaces used in applications aren't unique.
def check_url_namespaces_unique(app_configs, **kwargs): """ Warn if URL namespaces used in applications aren't unique. """ if not getattr(settings, 'ROOT_URLCONF', None): return [] from django.urls import get_resolver resolver = get_resolver() all_namespaces = _load_all_namespaces(r...
[ "def", "check_url_namespaces_unique", "(", "app_configs", ",", "*", "*", "kwargs", ")", ":", "if", "not", "getattr", "(", "settings", ",", "'ROOT_URLCONF'", ",", "None", ")", ":", "return", "[", "]", "from", "django", ".", "urls", "import", "get_resolver", ...
[ 30, 0 ]
[ 49, 17 ]
python
en
['en', 'error', 'th']
False
_load_all_namespaces
(resolver, parents=())
Recursively load all namespaces from URL patterns.
Recursively load all namespaces from URL patterns.
def _load_all_namespaces(resolver, parents=()): """ Recursively load all namespaces from URL patterns. """ url_patterns = getattr(resolver, 'url_patterns', []) namespaces = [ ':'.join(parents + (url.namespace,)) for url in url_patterns if getattr(url, 'namespace', None) is not None ...
[ "def", "_load_all_namespaces", "(", "resolver", ",", "parents", "=", "(", ")", ")", ":", "url_patterns", "=", "getattr", "(", "resolver", ",", "'url_patterns'", ",", "[", "]", ")", "namespaces", "=", "[", "':'", ".", "join", "(", "parents", "+", "(", "...
[ 52, 0 ]
[ 67, 21 ]
python
en
['en', 'error', 'th']
False
get_warning_for_invalid_pattern
(pattern)
Return a list containing a warning that the pattern is invalid. describe_pattern() cannot be used here, because we cannot rely on the urlpattern having regex or name attributes.
Return a list containing a warning that the pattern is invalid.
def get_warning_for_invalid_pattern(pattern): """ Return a list containing a warning that the pattern is invalid. describe_pattern() cannot be used here, because we cannot rely on the urlpattern having regex or name attributes. """ if isinstance(pattern, str): hint = ( "Try ...
[ "def", "get_warning_for_invalid_pattern", "(", "pattern", ")", ":", "if", "isinstance", "(", "pattern", ",", "str", ")", ":", "hint", "=", "(", "\"Try removing the string '{}'. The list of urlpatterns should not \"", "\"have a prefix string as the first element.\"", ".", "for...
[ 70, 0 ]
[ 92, 6 ]
python
en
['en', 'error', 'th']
False
_implementation
()
Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably...
Return a dict with the Python implementation and version.
def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and Py...
[ "def", "_implementation", "(", ")", ":", "implementation", "=", "platform", ".", "python_implementation", "(", ")", "if", "implementation", "==", "'CPython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "elif", "implementation", ...
[ 25, 0 ]
[ 55, 70 ]
python
en
['en', 'en', 'en']
True
info
()
Generate information for a bug report.
Generate information for a bug report.
def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } im...
[ "def", "info", "(", ")", ":", "try", ":", "platform_info", "=", "{", "'system'", ":", "platform", ".", "system", "(", ")", ",", "'release'", ":", "platform", ".", "release", "(", ")", ",", "}", "except", "IOError", ":", "platform_info", "=", "{", "'s...
[ 58, 0 ]
[ 109, 5 ]
python
en
['en', 'en', 'en']
True
main
()
Pretty-print the bug information as JSON.
Pretty-print the bug information as JSON.
def main(): """Pretty-print the bug information as JSON.""" print(json.dumps(info(), sort_keys=True, indent=2))
[ "def", "main", "(", ")", ":", "print", "(", "json", ".", "dumps", "(", "info", "(", ")", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ")", ")" ]
[ 112, 0 ]
[ 114, 55 ]
python
en
['en', 'en', 'en']
True
literals
(choices, prefix="", suffix="")
Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually.
Create a regex from a space-separated list of literal `choices`.
def literals(choices, prefix="", suffix=""): """ Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually. """ return "|".join(prefix + re.escape(c) + suffix for c in choices.split())
[ "def", "literals", "(", "choices", ",", "prefix", "=", "\"\"", ",", "suffix", "=", "\"\"", ")", ":", "return", "\"|\"", ".", "join", "(", "prefix", "+", "re", ".", "escape", "(", "c", ")", "+", "suffix", "for", "c", "in", "choices", ".", "split", ...
[ 19, 0 ]
[ 27, 76 ]
python
en
['en', 'error', 'th']
False
prepare_js_for_gettext
(js)
Convert the Javascript source `js` into something resembling C for xgettext. What actually happens is that all the regex literals are replaced with "REGEX".
Convert the Javascript source `js` into something resembling C for xgettext.
def prepare_js_for_gettext(js): """ Convert the Javascript source `js` into something resembling C for xgettext. What actually happens is that all the regex literals are replaced with "REGEX". """ def escape_quotes(m): """Used in a regex to properly escape double quotes.""" ...
[ "def", "prepare_js_for_gettext", "(", "js", ")", ":", "def", "escape_quotes", "(", "m", ")", ":", "\"\"\"Used in a regex to properly escape double quotes.\"\"\"", "s", "=", "m", ".", "group", "(", "0", ")", "if", "s", "==", "'\"'", ":", "return", "r'\\\"'", "e...
[ 185, 0 ]
[ 220, 21 ]
python
en
['en', 'error', 'th']
False
Lexer.lex
(self, text)
Lexically analyze `text`. Yields pairs (`name`, `tokentext`).
Lexically analyze `text`.
def lex(self, text): """ Lexically analyze `text`. Yields pairs (`name`, `tokentext`). """ end = len(text) state = self.state regexes = self.regexes toks = self.toks start = 0 while start < end: for match in regexes[state].fin...
[ "def", "lex", "(", "self", ",", "text", ")", ":", "end", "=", "len", "(", "text", ")", "state", "=", "self", ".", "state", "regexes", "=", "self", ".", "regexes", "toks", "=", "self", ".", "toks", "start", "=", "0", "while", "start", "<", "end", ...
[ 49, 4 ]
[ 73, 26 ]
python
en
['en', 'error', 'th']
False
DataTypesTestCase.test_year_boundaries
(self)
Year boundary tests (ticket #3689)
Year boundary tests (ticket #3689)
def test_year_boundaries(self): """Year boundary tests (ticket #3689)""" Donut.objects.create(name='Date Test 2007', baked_date=datetime.datetime(year=2007, month=12, day=31), consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59)) Don...
[ "def", "test_year_boundaries", "(", "self", ")", ":", "Donut", ".", "objects", ".", "create", "(", "name", "=", "'Date Test 2007'", ",", "baked_date", "=", "datetime", ".", "datetime", "(", "year", "=", "2007", ",", "month", "=", "12", ",", "day", "=", ...
[ 47, 4 ]
[ 69, 81 ]
python
en
['en', 'en', 'en']
True
DataTypesTestCase.test_textfields_unicode
(self)
Regression test for #10238: TextField values returned from the database should be unicode.
Regression test for #10238: TextField values returned from the database should be unicode.
def test_textfields_unicode(self): """Regression test for #10238: TextField values returned from the database should be unicode.""" d = Donut.objects.create(name='Jelly Donut', review='Outstanding') newd = Donut.objects.get(id=d.id) self.assertIsInstance(newd.review, six.text_typ...
[ "def", "test_textfields_unicode", "(", "self", ")", ":", "d", "=", "Donut", ".", "objects", ".", "create", "(", "name", "=", "'Jelly Donut'", ",", "review", "=", "'Outstanding'", ")", "newd", "=", "Donut", ".", "objects", ".", "get", "(", "id", "=", "d...
[ 71, 4 ]
[ 76, 57 ]
python
en
['en', 'en', 'en']
True
DataTypesTestCase.test_error_on_timezone
(self)
Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.
Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.
def test_error_on_timezone(self): """Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.""" dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=utc) d = Donut(name='Bear claw', consumed_at=dt) self.assertRaises(...
[ "def", "test_error_on_timezone", "(", "self", ")", ":", "dt", "=", "datetime", ".", "datetime", "(", "2008", ",", "8", ",", "31", ",", "16", ",", "20", ",", "tzinfo", "=", "utc", ")", "d", "=", "Donut", "(", "name", "=", "'Bear claw'", ",", "consum...
[ 79, 4 ]
[ 84, 45 ]
python
en
['en', 'en', 'en']
True
DataTypesTestCase.test_datefield_auto_now_add
(self)
Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime
Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime
def test_datefield_auto_now_add(self): """Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime""" b = RumBaba.objects.create() # Verify we didn't break DateTimeField behavior self.assertIsInstance(b.baked_timestamp, d...
[ "def", "test_datefield_auto_now_add", "(", "self", ")", ":", "b", "=", "RumBaba", ".", "objects", ".", "create", "(", ")", "# Verify we didn't break DateTimeField behavior", "self", ".", "assertIsInstance", "(", "b", ".", "baked_timestamp", ",", "datetime", ".", "...
[ 87, 4 ]
[ 95, 110 ]
python
en
['en', 'en', 'en']
True
usage
()
Print usage information for the program
Print usage information for the program
def usage(): '''Print usage information for the program''' argv0 = basename(sys.argv[0]) print """ Usage: ------ %(argv0)s [options] DEVICE1 DEVICE2 .... where DEVICE1, DEVICE2 etc, are specified via PCI "domain:bus:slot.func" syntax or "bus:slot.func" syntax. For devices bound to Linux kernel driver...
[ "def", "usage", "(", ")", ":", "argv0", "=", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", "print", "\"\"\"\nUsage:\n------\n\n %(argv0)s [options] DEVICE1 DEVICE2 ....\n\nwhere DEVICE1, DEVICE2 etc, are specified via PCI \"domain:bus:slot.func\" syntax\nor \"bus:slo...
[ 53, 0 ]
[ 112, 18 ]
python
en
['en', 'en', 'en']
True
check_output
(args, stderr=None)
Run a command and capture its output
Run a command and capture its output
def check_output(args, stderr=None): '''Run a command and capture its output''' return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr).communicate()[0]
[ "def", "check_output", "(", "args", ",", "stderr", "=", "None", ")", ":", "return", "subprocess", ".", "Popen", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "stderr", ")", ".", "communicate", "(", ")", "[", "0", "]"...
[ 116, 0 ]
[ 119, 59 ]
python
en
['en', 'en', 'en']
True
find_module
(mod)
find the .ko file for kernel module named mod. Searches the $RTE_SDK/$RTE_TARGET directory, the kernel modules directory and finally under the parent directory of the script
find the .ko file for kernel module named mod. Searches the $RTE_SDK/$RTE_TARGET directory, the kernel modules directory and finally under the parent directory of the script
def find_module(mod): '''find the .ko file for kernel module named mod. Searches the $RTE_SDK/$RTE_TARGET directory, the kernel modules directory and finally under the parent directory of the script ''' # check $RTE_SDK/$RTE_TARGET directory if 'RTE_SDK' in os.environ and 'RTE_TARGET' in os.envi...
[ "def", "find_module", "(", "mod", ")", ":", "# check $RTE_SDK/$RTE_TARGET directory", "if", "'RTE_SDK'", "in", "os", ".", "environ", "and", "'RTE_TARGET'", "in", "os", ".", "environ", ":", "path", "=", "\"%s/%s/kmod/%s.ko\"", "%", "(", "os", ".", "environ", "[...
[ 121, 0 ]
[ 152, 27 ]
python
en
['en', 'da', 'en']
True
check_modules
()
Checks that igb_uio is loaded
Checks that igb_uio is loaded
def check_modules(): '''Checks that igb_uio is loaded''' global dpdk_drivers fd = file("/proc/modules") loaded_mods = fd.readlines() fd.close() # list of supported modules mods = [{"Name" : driver, "Found" : False} for driver in dpdk_drivers] # first check if module is loaded for...
[ "def", "check_modules", "(", ")", ":", "global", "dpdk_drivers", "fd", "=", "file", "(", "\"/proc/modules\"", ")", "loaded_mods", "=", "fd", ".", "readlines", "(", ")", "fd", ".", "close", "(", ")", "# list of supported modules", "mods", "=", "[", "{", "\"...
[ 154, 0 ]
[ 184, 64 ]
python
en
['en', 'hmn', 'en']
True
has_driver
(dev_id)
return true if a device is assigned to a driver. False otherwise
return true if a device is assigned to a driver. False otherwise
def has_driver(dev_id): '''return true if a device is assigned to a driver. False otherwise''' return "Driver_str" in devices[dev_id]
[ "def", "has_driver", "(", "dev_id", ")", ":", "return", "\"Driver_str\"", "in", "devices", "[", "dev_id", "]" ]
[ 186, 0 ]
[ 188, 42 ]
python
en
['en', 'en', 'en']
True
get_pci_device_details
(dev_id)
This function gets additional details for a PCI device
This function gets additional details for a PCI device
def get_pci_device_details(dev_id): '''This function gets additional details for a PCI device''' device = {} extra_info = check_output(["lspci", "-vmmks", dev_id]).splitlines() # parse lspci details for line in extra_info: if len(line) == 0: continue name, value = line....
[ "def", "get_pci_device_details", "(", "dev_id", ")", ":", "device", "=", "{", "}", "extra_info", "=", "check_output", "(", "[", "\"lspci\"", ",", "\"-vmmks\"", ",", "dev_id", "]", ")", ".", "splitlines", "(", ")", "# parse lspci details", "for", "line", "in"...
[ 190, 0 ]
[ 213, 17 ]
python
en
['en', 'en', 'en']
True
get_nic_details
()
This function populates the "devices" dictionary. The keys used are the pci addresses (domain:bus:slot.func). The values are themselves dictionaries - one for each NIC.
This function populates the "devices" dictionary. The keys used are the pci addresses (domain:bus:slot.func). The values are themselves dictionaries - one for each NIC.
def get_nic_details(): '''This function populates the "devices" dictionary. The keys used are the pci addresses (domain:bus:slot.func). The values are themselves dictionaries - one for each NIC.''' global devices global dpdk_drivers # clear any old data devices = {} # first loop through...
[ "def", "get_nic_details", "(", ")", ":", "global", "devices", "global", "dpdk_drivers", "# clear any old data", "devices", "=", "{", "}", "# first loop through and read details for all devices", "# request machine readable format, with numeric IDs", "dev", "=", "{", "}", "dev...
[ 215, 0 ]
[ 276, 60 ]
python
en
['en', 'en', 'en']
True
dev_id_from_dev_name
(dev_name)
Take a device "name" - a string passed in by user to identify a NIC device, and determine the device id - i.e. the domain:bus:slot.func - for it, which can then be used to index into the devices array
Take a device "name" - a string passed in by user to identify a NIC device, and determine the device id - i.e. the domain:bus:slot.func - for it, which can then be used to index into the devices array
def dev_id_from_dev_name(dev_name): '''Take a device "name" - a string passed in by user to identify a NIC device, and determine the device id - i.e. the domain:bus:slot.func - for it, which can then be used to index into the devices array''' dev = None # check if it's already a suitable index i...
[ "def", "dev_id_from_dev_name", "(", "dev_name", ")", ":", "dev", "=", "None", "# check if it's already a suitable index", "if", "dev_name", "in", "devices", ":", "return", "dev_name", "# check if it's an index just missing the domain part", "elif", "\"0000:\"", "+", "dev_na...
[ 278, 0 ]
[ 297, 15 ]
python
en
['en', 'en', 'en']
True
unbind_one
(dev_id, force)
Unbind the device identified by "dev_id" from its current driver
Unbind the device identified by "dev_id" from its current driver
def unbind_one(dev_id, force): '''Unbind the device identified by "dev_id" from its current driver''' dev = devices[dev_id] if not has_driver(dev_id): print "%s %s %s is not currently managed by any driver\n" % \ (dev["Slot"], dev["Device_str"], dev["Interface"]) return # pr...
[ "def", "unbind_one", "(", "dev_id", ",", "force", ")", ":", "dev", "=", "devices", "[", "dev_id", "]", "if", "not", "has_driver", "(", "dev_id", ")", ":", "print", "\"%s %s %s is not currently managed by any driver\\n\"", "%", "(", "dev", "[", "\"Slot\"", "]",...
[ 299, 0 ]
[ 321, 13 ]
python
en
['en', 'en', 'en']
True
bind_one
(dev_id, driver, force)
Bind the device given by "dev_id" to the driver "driver". If the device is already bound to a different driver, it will be unbound first
Bind the device given by "dev_id" to the driver "driver". If the device is already bound to a different driver, it will be unbound first
def bind_one(dev_id, driver, force): '''Bind the device given by "dev_id" to the driver "driver". If the device is already bound to a different driver, it will be unbound first''' dev = devices[dev_id] saved_driver = None # used to rollback any unbind in case of failure # prevent disconnection of o...
[ "def", "bind_one", "(", "dev_id", ",", "driver", ",", "force", ")", ":", "dev", "=", "devices", "[", "dev_id", "]", "saved_driver", "=", "None", "# used to rollback any unbind in case of failure", "# prevent disconnection of our ssh session", "if", "dev", "[", "\"Ssh_...
[ 323, 0 ]
[ 383, 14 ]
python
en
['en', 'en', 'en']
True
unbind_all
(dev_list, force=False)
Unbind method, takes a list of device locations
Unbind method, takes a list of device locations
def unbind_all(dev_list, force=False): """Unbind method, takes a list of device locations""" dev_list = map(dev_id_from_dev_name, dev_list) for d in dev_list: unbind_one(d, force)
[ "def", "unbind_all", "(", "dev_list", ",", "force", "=", "False", ")", ":", "dev_list", "=", "map", "(", "dev_id_from_dev_name", ",", "dev_list", ")", "for", "d", "in", "dev_list", ":", "unbind_one", "(", "d", ",", "force", ")" ]
[ 386, 0 ]
[ 390, 28 ]
python
en
['en', 'en', 'en']
True
bind_all
(dev_list, driver, force=False)
Bind method, takes a list of device locations
Bind method, takes a list of device locations
def bind_all(dev_list, driver, force=False): """Bind method, takes a list of device locations""" global devices dev_list = map(dev_id_from_dev_name, dev_list) for d in dev_list: bind_one(d, driver, force) # when binding devices to a generic driver (i.e. one that doesn't have a # PCI I...
[ "def", "bind_all", "(", "dev_list", ",", "driver", ",", "force", "=", "False", ")", ":", "global", "devices", "dev_list", "=", "map", "(", "dev_id_from_dev_name", ",", "dev_list", ")", "for", "d", "in", "dev_list", ":", "bind_one", "(", "d", ",", "driver...
[ 392, 0 ]
[ 417, 32 ]
python
en
['en', 'en', 'en']
True
display_devices
(title, dev_list, extra_params = None)
Displays to the user the details of a list of devices given in "dev_list" The "extra_params" parameter, if given, should contain a string with %()s fields in it for replacement by the named fields in each device's dictionary.
Displays to the user the details of a list of devices given in "dev_list" The "extra_params" parameter, if given, should contain a string with %()s fields in it for replacement by the named fields in each device's dictionary.
def display_devices(title, dev_list, extra_params = None): '''Displays to the user the details of a list of devices given in "dev_list" The "extra_params" parameter, if given, should contain a string with %()s fields in it for replacement by the named fields in each device's dictionary.''' strings =...
[ "def", "display_devices", "(", "title", ",", "dev_list", ",", "extra_params", "=", "None", ")", ":", "strings", "=", "[", "]", "# this holds the strings to print. We sort before printing", "print", "\"\\n%s\"", "%", "title", "print", "\"=\"", "*", "len", "(", "tit...
[ 419, 0 ]
[ 438, 28 ]
python
en
['en', 'en', 'en']
True
show_status
()
Function called when the script is passed the "--status" option. Displays to the user what devices are bound to the igb_uio driver, the kernel driver or to no driver
Function called when the script is passed the "--status" option. Displays to the user what devices are bound to the igb_uio driver, the kernel driver or to no driver
def show_status(): '''Function called when the script is passed the "--status" option. Displays to the user what devices are bound to the igb_uio driver, the kernel driver or to no driver''' global dpdk_drivers kernel_drv = [] dpdk_drv = [] no_drv = [] # split our list of devices into t...
[ "def", "show_status", "(", ")", ":", "global", "dpdk_drivers", "kernel_drv", "=", "[", "]", "dpdk_drv", "=", "[", "]", "no_drv", "=", "[", "]", "# split our list of devices into the three categories above", "for", "d", "in", "devices", ".", "keys", "(", ")", "...
[ 440, 0 ]
[ 465, 44 ]
python
en
['en', 'en', 'en']
True
parse_args
()
Parses the command-line arguments given by the user and takes the appropriate action for each
Parses the command-line arguments given by the user and takes the appropriate action for each
def parse_args(): '''Parses the command-line arguments given by the user and takes the appropriate action for each''' global b_flag global status_flag global force_flag global args if len(sys.argv) <= 1: usage() sys.exit(0) try: opts, args = getopt.getopt(sys.arg...
[ "def", "parse_args", "(", ")", ":", "global", "b_flag", "global", "status_flag", "global", "force_flag", "global", "args", "if", "len", "(", "sys", ".", "argv", ")", "<=", "1", ":", "usage", "(", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", ...
[ 467, 0 ]
[ 502, 28 ]
python
en
['en', 'en', 'en']
True
do_arg_actions
()
do the actual action requested by the user
do the actual action requested by the user
def do_arg_actions(): '''do the actual action requested by the user''' global b_flag global status_flag global force_flag global args if b_flag is None and not status_flag: print "Error: No action specified for devices. Please give a -b or -u option" print "Run '%s --usage' for ...
[ "def", "do_arg_actions", "(", ")", ":", "global", "b_flag", "global", "status_flag", "global", "force_flag", "global", "args", "if", "b_flag", "is", "None", "and", "not", "status_flag", ":", "print", "\"Error: No action specified for devices. Please give a -b or -u option...
[ 504, 0 ]
[ 528, 21 ]
python
en
['en', 'en', 'en']
True
main
()
program main function
program main function
def main(): '''program main function''' parse_args() check_modules() get_nic_details() do_arg_actions()
[ "def", "main", "(", ")", ":", "parse_args", "(", ")", "check_modules", "(", ")", "get_nic_details", "(", ")", "do_arg_actions", "(", ")" ]
[ 530, 0 ]
[ 535, 20 ]
python
en
['en', 'no', 'en']
True
add_level_messages
(storage)
Adds 6 messages from different levels (including a custom one) to a storage instance.
Adds 6 messages from different levels (including a custom one) to a storage instance.
def add_level_messages(storage): """ Adds 6 messages from different levels (including a custom one) to a storage instance. """ storage.add(constants.INFO, 'A generic info message') storage.add(29, 'Some custom level') storage.add(constants.DEBUG, 'A debugging message', extra_tags='extra-tag'...
[ "def", "add_level_messages", "(", "storage", ")", ":", "storage", ".", "add", "(", "constants", ".", "INFO", ",", "'A generic info message'", ")", "storage", ".", "add", "(", "29", ",", "'Some custom level'", ")", "storage", ".", "add", "(", "constants", "."...
[ 21, 0 ]
[ 31, 57 ]
python
en
['en', 'error', 'th']
False
BaseTests.get_storage
(self, data=None)
Returns the storage backend, setting its loaded data to the ``data`` argument. This method avoids the storage ``_get`` method from getting called so that other parts of the storage backend can be tested independent of the message retrieval logic.
Returns the storage backend, setting its loaded data to the ``data`` argument.
def get_storage(self, data=None): """ Returns the storage backend, setting its loaded data to the ``data`` argument. This method avoids the storage ``_get`` method from getting called so that other parts of the storage backend can be tested independent of the message ret...
[ "def", "get_storage", "(", "self", ",", "data", "=", "None", ")", ":", "storage", "=", "self", ".", "storage_class", "(", "self", ".", "get_request", "(", ")", ")", "storage", ".", "_loaded_data", "=", "data", "or", "[", "]", "return", "storage" ]
[ 79, 4 ]
[ 90, 22 ]
python
en
['en', 'error', 'th']
False
BaseTests.test_full_request_response_cycle
(self)
With the message middleware enabled, tests that messages are properly stored and then retrieved across the full request/redirect/response cycle.
With the message middleware enabled, tests that messages are properly stored and then retrieved across the full request/redirect/response cycle.
def test_full_request_response_cycle(self): """ With the message middleware enabled, tests that messages are properly stored and then retrieved across the full request/redirect/response cycle. """ data = { 'messages': ['Test message %d' % x for x in range(5)],...
[ "def", "test_full_request_response_cycle", "(", "self", ")", ":", "data", "=", "{", "'messages'", ":", "[", "'Test message %d'", "%", "x", "for", "x", "in", "range", "(", "5", ")", "]", ",", "}", "show_url", "=", "reverse", "(", "'show_message'", ")", "f...
[ 151, 4 ]
[ 169, 50 ]
python
en
['en', 'error', 'th']
False
BaseTests.test_multiple_posts
(self)
Tests that messages persist properly when multiple POSTs are made before a GET.
Tests that messages persist properly when multiple POSTs are made before a GET.
def test_multiple_posts(self): """ Tests that messages persist properly when multiple POSTs are made before a GET. """ data = { 'messages': ['Test message %d' % x for x in range(5)], } show_url = reverse('show_message') messages = [] fo...
[ "def", "test_multiple_posts", "(", "self", ")", ":", "data", "=", "{", "'messages'", ":", "[", "'Test message %d'", "%", "x", "for", "x", "in", "range", "(", "5", ")", "]", ",", "}", "show_url", "=", "reverse", "(", "'show_message'", ")", "messages", "...
[ 198, 4 ]
[ 216, 46 ]
python
en
['en', 'error', 'th']
False
BaseTests.test_middleware_disabled
(self)
Tests that, when the middleware is disabled, an exception is raised when one attempts to store a message.
Tests that, when the middleware is disabled, an exception is raised when one attempts to store a message.
def test_middleware_disabled(self): """ Tests that, when the middleware is disabled, an exception is raised when one attempts to store a message. """ data = { 'messages': ['Test message %d' % x for x in range(5)], } reverse('show_message') for ...
[ "def", "test_middleware_disabled", "(", "self", ")", ":", "data", "=", "{", "'messages'", ":", "[", "'Test message %d'", "%", "x", "for", "x", "in", "range", "(", "5", ")", "]", ",", "}", "reverse", "(", "'show_message'", ")", "for", "level", "in", "("...
[ 224, 4 ]
[ 236, 48 ]
python
en
['en', 'error', 'th']
False
BaseTests.test_middleware_disabled_fail_silently
(self)
Tests that, when the middleware is disabled, an exception is not raised if 'fail_silently' = True
Tests that, when the middleware is disabled, an exception is not raised if 'fail_silently' = True
def test_middleware_disabled_fail_silently(self): """ Tests that, when the middleware is disabled, an exception is not raised if 'fail_silently' = True """ data = { 'messages': ['Test message %d' % x for x in range(5)], 'fail_silently': True, } ...
[ "def", "test_middleware_disabled_fail_silently", "(", "self", ")", ":", "data", "=", "{", "'messages'", ":", "[", "'Test message %d'", "%", "x", "for", "x", "in", "range", "(", "5", ")", "]", ",", "'fail_silently'", ":", "True", ",", "}", "show_url", "=", ...
[ 243, 4 ]
[ 257, 60 ]
python
en
['en', 'error', 'th']
False
BaseTests.stored_messages_count
(self, storage, response)
Returns the number of messages being stored after a ``storage.update()`` call.
Returns the number of messages being stored after a ``storage.update()`` call.
def stored_messages_count(self, storage, response): """ Returns the number of messages being stored after a ``storage.update()`` call. """ raise NotImplementedError('This method must be set by a subclass.')
[ "def", "stored_messages_count", "(", "self", ",", "storage", ",", "response", ")", ":", "raise", "NotImplementedError", "(", "'This method must be set by a subclass.'", ")" ]
[ 259, 4 ]
[ 264, 75 ]
python
en
['en', 'error', 'th']
False
BaseTests.test_existing_read
(self)
Tests that reading the existing storage doesn't cause the data to be lost.
Tests that reading the existing storage doesn't cause the data to be lost.
def test_existing_read(self): """ Tests that reading the existing storage doesn't cause the data to be lost. """ storage = self.get_existing_storage() self.assertFalse(storage.used) # After iterating the storage engine directly, the used flag is set. data ...
[ "def", "test_existing_read", "(", "self", ")", ":", "storage", "=", "self", ".", "get_existing_storage", "(", ")", "self", ".", "assertFalse", "(", "storage", ".", "used", ")", "# After iterating the storage engine directly, the used flag is set.", "data", "=", "list"...
[ 274, 4 ]
[ 285, 45 ]
python
en
['en', 'error', 'th']
False
Command.set_options
(self, **options)
Set instance variables based on an options dict
Set instance variables based on an options dict
def set_options(self, **options): """ Set instance variables based on an options dict """ self.interactive = options['interactive'] self.verbosity = options['verbosity'] self.symlink = options['link'] self.clear = options['clear'] self.dry_run = options['d...
[ "def", "set_options", "(", "self", ",", "*", "*", "options", ")", ":", "self", ".", "interactive", "=", "options", "[", "'interactive'", "]", "self", ".", "verbosity", "=", "options", "[", "'verbosity'", "]", "self", ".", "symlink", "=", "options", "[", ...
[ 64, 4 ]
[ 77, 51 ]
python
en
['en', 'error', 'th']
False
Command.collect
(self)
Perform the bulk of the work of collectstatic. Split off from handle() to facilitate testing.
Perform the bulk of the work of collectstatic.
def collect(self): """ Perform the bulk of the work of collectstatic. Split off from handle() to facilitate testing. """ if self.symlink and not self.local: raise CommandError("Can't symlink to a remote destination.") if self.clear: self.clear_di...
[ "def", "collect", "(", "self", ")", ":", "if", "self", ".", "symlink", "and", "not", "self", ".", "local", ":", "raise", "CommandError", "(", "\"Can't symlink to a remote destination.\"", ")", "if", "self", ".", "clear", ":", "self", ".", "clear_dir", "(", ...
[ 79, 4 ]
[ 132, 9 ]
python
en
['en', 'error', 'th']
False
Command.log
(self, msg, level=2)
Small log helper
Small log helper
def log(self, msg, level=2): """ Small log helper """ if self.verbosity >= level: self.stdout.write(msg)
[ "def", "log", "(", "self", ",", "msg", ",", "level", "=", "2", ")", ":", "if", "self", ".", "verbosity", ">=", "level", ":", "self", ".", "stdout", ".", "write", "(", "msg", ")" ]
[ 188, 4 ]
[ 193, 34 ]
python
en
['en', 'error', 'th']
False
Command.clear_dir
(self, path)
Deletes the given relative path using the destination storage backend.
Deletes the given relative path using the destination storage backend.
def clear_dir(self, path): """ Deletes the given relative path using the destination storage backend. """ dirs, files = self.storage.listdir(path) for f in files: fpath = os.path.join(path, f) if self.dry_run: self.log("Pretending to delete...
[ "def", "clear_dir", "(", "self", ",", "path", ")", ":", "dirs", ",", "files", "=", "self", ".", "storage", ".", "listdir", "(", "path", ")", "for", "f", "in", "files", ":", "fpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")...
[ 198, 4 ]
[ 212, 49 ]
python
en
['en', 'error', 'th']
False
Command.delete_file
(self, path, prefixed_path, source_storage)
Checks if the target file should be deleted if it already exists
Checks if the target file should be deleted if it already exists
def delete_file(self, path, prefixed_path, source_storage): """ Checks if the target file should be deleted if it already exists """ if self.storage.exists(prefixed_path): try: # When was the target file modified last time? target_last_modified...
[ "def", "delete_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "if", "self", ".", "storage", ".", "exists", "(", "prefixed_path", ")", ":", "try", ":", "# When was the target file modified last time?", "target_last_modified", ...
[ 214, 4 ]
[ 256, 19 ]
python
en
['en', 'error', 'th']
False
Command.link_file
(self, path, prefixed_path, source_storage)
Attempt to link ``path``
Attempt to link ``path``
def link_file(self, path, prefixed_path, source_storage): """ Attempt to link ``path`` """ # Skip this file if it was already copied earlier if prefixed_path in self.symlinked_files: return self.log("Skipping '%s' (already linked earlier)" % path) # Delete the...
[ "def", "link_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "# Skip this file if it was already copied earlier", "if", "prefixed_path", "in", "self", ".", "symlinked_files", ":", "return", "self", ".", "log", "(", "\"Skipping...
[ 258, 4 ]
[ 295, 54 ]
python
en
['en', 'error', 'th']
False
Command.copy_file
(self, path, prefixed_path, source_storage)
Attempt to copy ``path`` with storage
Attempt to copy ``path`` with storage
def copy_file(self, path, prefixed_path, source_storage): """ Attempt to copy ``path`` with storage """ # Skip this file if it was already copied earlier if prefixed_path in self.copied_files: return self.log("Skipping '%s' (already copied earlier)" % path) # ...
[ "def", "copy_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "# Skip this file if it was already copied earlier", "if", "prefixed_path", "in", "self", ".", "copied_files", ":", "return", "self", ".", "log", "(", "\"Skipping '%...
[ 297, 4 ]
[ 317, 51 ]
python
en
['en', 'error', 'th']
False
get_callable
(lookup_view)
Return a callable corresponding to lookup_view. * If lookup_view is already a callable, return it. * If lookup_view is a string import path that can be resolved to a callable, import that callable and return it, otherwise raise an exception (ImportError or ViewDoesNotExist).
Return a callable corresponding to lookup_view. * If lookup_view is already a callable, return it. * If lookup_view is a string import path that can be resolved to a callable, import that callable and return it, otherwise raise an exception (ImportError or ViewDoesNotExist).
def get_callable(lookup_view): """ Return a callable corresponding to lookup_view. * If lookup_view is already a callable, return it. * If lookup_view is a string import path that can be resolved to a callable, import that callable and return it, otherwise raise an exception (ImportError or ...
[ "def", "get_callable", "(", "lookup_view", ")", ":", "if", "callable", "(", "lookup_view", ")", ":", "return", "lookup_view", "if", "not", "isinstance", "(", "lookup_view", ",", "str", ")", ":", "raise", "ViewDoesNotExist", "(", "\"'%s' is not a callable or a dot-...
[ 8, 0 ]
[ 51, 28 ]
python
en
['en', 'error', 'th']
False
DatabaseValidation.check_field_type
(self, field, field_type)
Oracle doesn't support a database index on some data types.
Oracle doesn't support a database index on some data types.
def check_field_type(self, field, field_type): """Oracle doesn't support a database index on some data types.""" errors = [] if field.db_index and field_type.lower() in self.connection._limited_data_types: errors.append( checks.Warning( 'Oracle doe...
[ "def", "check_field_type", "(", "self", ",", "field", ",", "field_type", ")", ":", "errors", "=", "[", "]", "if", "field", ".", "db_index", "and", "field_type", ".", "lower", "(", ")", "in", "self", ".", "connection", ".", "_limited_data_types", ":", "er...
[ 5, 4 ]
[ 21, 21 ]
python
en
['en', 'en', 'en']
True
add_srs_entry
(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None, database=None)
This function takes a GDAL SpatialReference system and adds its information to the `spatial_ref_sys` table of the spatial backend. Doing this enables database-level spatial transformations for the backend. Thus, this utility is useful for adding spatial reference systems not included by default with ...
This function takes a GDAL SpatialReference system and adds its information to the `spatial_ref_sys` table of the spatial backend. Doing this enables database-level spatial transformations for the backend. Thus, this utility is useful for adding spatial reference systems not included by default with ...
def add_srs_entry(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None, database=None): """ This function takes a GDAL SpatialReference system and adds its information to the `spatial_ref_sys` table of the spatial backend. Doing this enables database-level spatial transformations ...
[ "def", "add_srs_entry", "(", "srs", ",", "auth_name", "=", "'EPSG'", ",", "auth_srid", "=", "None", ",", "ref_sys_name", "=", "None", ",", "database", "=", "None", ")", ":", "if", "not", "database", ":", "database", "=", "DEFAULT_DB_ALIAS", "connection", "...
[ 4, 0 ]
[ 76, 62 ]
python
en
['en', 'error', 'th']
False
_fixup_find_links
(find_links)
Ensure find-links option end-up being a list of strings.
Ensure find-links option end-up being a list of strings.
def _fixup_find_links(find_links): """Ensure find-links option end-up being a list of strings.""" if isinstance(find_links, six.string_types): return find_links.split() assert isinstance(find_links, (tuple, list)) return find_links
[ "def", "_fixup_find_links", "(", "find_links", ")", ":", "if", "isinstance", "(", "find_links", ",", "six", ".", "string_types", ")", ":", "return", "find_links", ".", "split", "(", ")", "assert", "isinstance", "(", "find_links", ",", "(", "tuple", ",", "l...
[ 15, 0 ]
[ 20, 21 ]
python
en
['en', 'en', 'en']
True
_legacy_fetch_build_egg
(dist, req)
Fetch an egg needed for building. Legacy path using EasyInstall.
Fetch an egg needed for building.
def _legacy_fetch_build_egg(dist, req): """Fetch an egg needed for building. Legacy path using EasyInstall. """ tmp_dist = dist.__class__({'script_args': ['easy_install']}) opts = tmp_dist.get_option_dict('easy_install') opts.clear() opts.update( (k, v) for k, v in dist.get_...
[ "def", "_legacy_fetch_build_egg", "(", "dist", ",", "req", ")", ":", "tmp_dist", "=", "dist", ".", "__class__", "(", "{", "'script_args'", ":", "[", "'easy_install'", "]", "}", ")", "opts", "=", "tmp_dist", ".", "get_option_dict", "(", "'easy_install'", ")",...
[ 23, 0 ]
[ 52, 32 ]
python
en
['en', 'en', 'en']
True
fetch_build_egg
(dist, req)
Fetch an egg needed for building. Use pip/wheel to fetch/build a wheel.
Fetch an egg needed for building.
def fetch_build_egg(dist, req): """Fetch an egg needed for building. Use pip/wheel to fetch/build a wheel.""" # Check pip is available. try: pkg_resources.get_distribution('pip') except pkg_resources.DistributionNotFound: dist.announce( 'WARNING: The pip package is not a...
[ "def", "fetch_build_egg", "(", "dist", ",", "req", ")", ":", "# Check pip is available.", "try", ":", "pkg_resources", ".", "get_distribution", "(", "'pip'", ")", "except", "pkg_resources", ".", "DistributionNotFound", ":", "dist", ".", "announce", "(", "'WARNING:...
[ 55, 0 ]
[ 137, 19 ]
python
en
['en', 'en', 'en']
True
strip_marker
(req)
Return a new requirement without the environment marker to avoid calling pip with something like `babel; extra == "i18n"`, which would always be ignored.
Return a new requirement without the environment marker to avoid calling pip with something like `babel; extra == "i18n"`, which would always be ignored.
def strip_marker(req): """ Return a new requirement without the environment marker to avoid calling pip with something like `babel; extra == "i18n"`, which would always be ignored. """ # create a copy to avoid mutating the input req = pkg_resources.Requirement.parse(str(req)) req.marker ...
[ "def", "strip_marker", "(", "req", ")", ":", "# create a copy to avoid mutating the input", "req", "=", "pkg_resources", ".", "Requirement", ".", "parse", "(", "str", "(", "req", ")", ")", "req", ".", "marker", "=", "None", "return", "req" ]
[ 140, 0 ]
[ 149, 14 ]
python
en
['en', 'error', 'th']
False
csrf
(request)
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware
def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debu...
[ "def", "csrf", "(", "request", ")", ":", "def", "_get_val", "(", ")", ":", "token", "=", "get_token", "(", "request", ")", "if", "token", "is", "None", ":", "# In order to be able to provide debugging info in the", "# case of misconfiguration, we use a sentinel value", ...
[ 17, 0 ]
[ 33, 37 ]
python
en
['en', 'error', 'th']
False
debug
(request)
Returns context variables helpful for debugging.
Returns context variables helpful for debugging.
def debug(request): """ Returns context variables helpful for debugging. """ context_extras = {} if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS: context_extras['debug'] = True from django.db import connection # Return a lazy reference that comp...
[ "def", "debug", "(", "request", ")", ":", "context_extras", "=", "{", "}", "if", "settings", ".", "DEBUG", "and", "request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ")", "in", "settings", ".", "INTERNAL_IPS", ":", "context_extras", "[", "'debug'", ...
[ 36, 0 ]
[ 47, 25 ]
python
en
['en', 'error', 'th']
False
static
(request)
Adds static-related context variables to the context.
Adds static-related context variables to the context.
def static(request): """ Adds static-related context variables to the context. """ return {'STATIC_URL': settings.STATIC_URL}
[ "def", "static", "(", "request", ")", ":", "return", "{", "'STATIC_URL'", ":", "settings", ".", "STATIC_URL", "}" ]
[ 67, 0 ]
[ 72, 46 ]
python
en
['en', 'error', 'th']
False
media
(request)
Adds media-related context variables to the context.
Adds media-related context variables to the context.
def media(request): """ Adds media-related context variables to the context. """ return {'MEDIA_URL': settings.MEDIA_URL}
[ "def", "media", "(", "request", ")", ":", "return", "{", "'MEDIA_URL'", ":", "settings", ".", "MEDIA_URL", "}" ]
[ 75, 0 ]
[ 80, 44 ]
python
en
['en', 'error', 'th']
False
projected_gradient_descent
( model_fn, x, eps, eps_iter, nb_iter, norm, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=None, rand_minmax=0.3, )
This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_init is set to 0. or the Madry et al. (2017) method when rand_minmax is larger than 0. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf...
This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_init is set to 0. or the Madry et al. (2017) method when rand_minmax is larger than 0. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf...
def projected_gradient_descent( model_fn, x, eps, eps_iter, nb_iter, norm, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=None, rand_minmax=0.3, ): """ This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_ini...
[ "def", "projected_gradient_descent", "(", "model_fn", ",", "x", ",", "eps", ",", "eps_iter", ",", "nb_iter", ",", "norm", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "rand_init", ...
[ 6, 0 ]
[ 98, 16 ]
python
en
['en', 'error', 'th']
False