repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
albu/albumentations
albumentations/augmentations/functional.py
keypoint_vflip
def keypoint_vflip(kp, rows, cols): """Flip a keypoint vertically around the x-axis.""" x, y, angle, scale = kp c = math.cos(angle) s = math.sin(angle) angle = math.atan2(-s, c) return [x, (rows - 1) - y, angle, scale]
python
def keypoint_vflip(kp, rows, cols): """Flip a keypoint vertically around the x-axis.""" x, y, angle, scale = kp c = math.cos(angle) s = math.sin(angle) angle = math.atan2(-s, c) return [x, (rows - 1) - y, angle, scale]
[ "def", "keypoint_vflip", "(", "kp", ",", "rows", ",", "cols", ")", ":", "x", ",", "y", ",", "angle", ",", "scale", "=", "kp", "c", "=", "math", ".", "cos", "(", "angle", ")", "s", "=", "math", ".", "sin", "(", "angle", ")", "angle", "=", "mat...
Flip a keypoint vertically around the x-axis.
[ "Flip", "a", "keypoint", "vertically", "around", "the", "x", "-", "axis", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1042-L1048
train
albu/albumentations
albumentations/augmentations/functional.py
keypoint_flip
def keypoint_flip(bbox, d, rows, cols): """Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. """ if d == 0: bbox = keypoint_vflip(bbox, rows, cols) elif d == 1: bbox = keypoint_hflip...
python
def keypoint_flip(bbox, d, rows, cols): """Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. """ if d == 0: bbox = keypoint_vflip(bbox, rows, cols) elif d == 1: bbox = keypoint_hflip...
[ "def", "keypoint_flip", "(", "bbox", ",", "d", ",", "rows", ",", "cols", ")", ":", "if", "d", "==", "0", ":", "bbox", "=", "keypoint_vflip", "(", "bbox", ",", "rows", ",", "cols", ")", "elif", "d", "==", "1", ":", "bbox", "=", "keypoint_hflip", "...
Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1.
[ "Flip", "a", "keypoint", "either", "vertically", "horizontally", "or", "both", "depending", "on", "the", "value", "of", "d", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1060-L1076
train
albu/albumentations
albumentations/augmentations/functional.py
keypoint_rot90
def keypoint_rot90(keypoint, factor, rows, cols, **params): """Rotates a keypoint by 90 degrees CCW (see np.rot90) Args: keypoint (tuple): A tuple (x, y, angle, scale). factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image rows. cols (int)...
python
def keypoint_rot90(keypoint, factor, rows, cols, **params): """Rotates a keypoint by 90 degrees CCW (see np.rot90) Args: keypoint (tuple): A tuple (x, y, angle, scale). factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image rows. cols (int)...
[ "def", "keypoint_rot90", "(", "keypoint", ",", "factor", ",", "rows", ",", "cols", ",", "*", "*", "params", ")", ":", "if", "factor", "<", "0", "or", "factor", ">", "3", ":", "raise", "ValueError", "(", "'Parameter n must be in range [0;3]'", ")", "x", "...
Rotates a keypoint by 90 degrees CCW (see np.rot90) Args: keypoint (tuple): A tuple (x, y, angle, scale). factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image rows. cols (int): Image cols.
[ "Rotates", "a", "keypoint", "by", "90", "degrees", "CCW", "(", "see", "np", ".", "rot90", ")" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1079-L1097
train
albu/albumentations
albumentations/augmentations/functional.py
keypoint_scale
def keypoint_scale(keypoint, scale_x, scale_y, **params): """Scales a keypoint by scale_x and scale_y.""" x, y, a, s = keypoint return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)]
python
def keypoint_scale(keypoint, scale_x, scale_y, **params): """Scales a keypoint by scale_x and scale_y.""" x, y, a, s = keypoint return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)]
[ "def", "keypoint_scale", "(", "keypoint", ",", "scale_x", ",", "scale_y", ",", "*", "*", "params", ")", ":", "x", ",", "y", ",", "a", ",", "s", "=", "keypoint", "return", "[", "x", "*", "scale_x", ",", "y", "*", "scale_y", ",", "a", ",", "s", "...
Scales a keypoint by scale_x and scale_y.
[ "Scales", "a", "keypoint", "by", "scale_x", "and", "scale_y", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1107-L1110
train
albu/albumentations
albumentations/augmentations/functional.py
crop_keypoint_by_coords
def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols): """Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ x, y, a, s = keypoint x1, y1, x2, y2 = crop_coords cropped_...
python
def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols): """Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ x, y, a, s = keypoint x1, y1, x2, y2 = crop_coords cropped_...
[ "def", "crop_keypoint_by_coords", "(", "keypoint", ",", "crop_coords", ",", "crop_height", ",", "crop_width", ",", "rows", ",", "cols", ")", ":", "x", ",", "y", ",", "a", ",", "s", "=", "keypoint", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "crop_co...
Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop.
[ "Crop", "a", "keypoint", "using", "the", "provided", "coordinates", "of", "bottom", "-", "left", "and", "top", "-", "right", "corners", "in", "pixels", "and", "the", "required", "height", "and", "width", "of", "the", "crop", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1113-L1120
train
albu/albumentations
albumentations/augmentations/functional.py
py3round
def py3round(number): """Unified rounding in all python versions.""" if abs(round(number) - number) == 0.5: return int(2.0 * round(number / 2.0)) return int(round(number))
python
def py3round(number): """Unified rounding in all python versions.""" if abs(round(number) - number) == 0.5: return int(2.0 * round(number / 2.0)) return int(round(number))
[ "def", "py3round", "(", "number", ")", ":", "if", "abs", "(", "round", "(", "number", ")", "-", "number", ")", "==", "0.5", ":", "return", "int", "(", "2.0", "*", "round", "(", "number", "/", "2.0", ")", ")", "return", "int", "(", "round", "(", ...
Unified rounding in all python versions.
[ "Unified", "rounding", "in", "all", "python", "versions", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1133-L1138
train
albu/albumentations
albumentations/augmentations/transforms.py
RandomRotate90.apply
def apply(self, img, factor=0, **params): """ Args: factor (int): number of times the input will be rotated by 90 degrees. """ return np.ascontiguousarray(np.rot90(img, factor))
python
def apply(self, img, factor=0, **params): """ Args: factor (int): number of times the input will be rotated by 90 degrees. """ return np.ascontiguousarray(np.rot90(img, factor))
[ "def", "apply", "(", "self", ",", "img", ",", "factor", "=", "0", ",", "*", "*", "params", ")", ":", "return", "np", ".", "ascontiguousarray", "(", "np", ".", "rot90", "(", "img", ",", "factor", ")", ")" ]
Args: factor (int): number of times the input will be rotated by 90 degrees.
[ "Args", ":", "factor", "(", "int", ")", ":", "number", "of", "times", "the", "input", "will", "be", "rotated", "by", "90", "degrees", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/transforms.py#L319-L324
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
normalize_bbox
def normalize_bbox(bbox, rows, cols): """Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates by image height. """ if rows == 0: raise ValueError('Argument rows cannot be zero') if cols == 0: raise ValueError('Argument cols cannot be zero') ...
python
def normalize_bbox(bbox, rows, cols): """Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates by image height. """ if rows == 0: raise ValueError('Argument rows cannot be zero') if cols == 0: raise ValueError('Argument cols cannot be zero') ...
[ "def", "normalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "if", "rows", "==", "0", ":", "raise", "ValueError", "(", "'Argument rows cannot be zero'", ")", "if", "cols", "==", "0", ":", "raise", "ValueError", "(", "'Argument cols cannot be zero'...
Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates by image height.
[ "Normalize", "coordinates", "of", "a", "bounding", "box", ".", "Divide", "x", "-", "coordinates", "by", "image", "width", "and", "y", "-", "coordinates", "by", "image", "height", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L10-L20
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
denormalize_bbox
def denormalize_bbox(bbox, rows, cols): """Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`. """ if rows == 0: raise ValueError('Argument ...
python
def denormalize_bbox(bbox, rows, cols): """Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`. """ if rows == 0: raise ValueError('Argument ...
[ "def", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "if", "rows", "==", "0", ":", "raise", "ValueError", "(", "'Argument rows cannot be zero'", ")", "if", "cols", "==", "0", ":", "raise", "ValueError", "(", "'Argument cols cannot be zer...
Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.
[ "Denormalize", "coordinates", "of", "a", "bounding", "box", ".", "Multiply", "x", "-", "coordinates", "by", "image", "width", "and", "y", "-", "coordinates", "by", "image", "height", ".", "This", "is", "an", "inverse", "operation", "for", ":", "func", ":",...
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L23-L34
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
normalize_bboxes
def normalize_bboxes(bboxes, rows, cols): """Normalize a list of bounding boxes.""" return [normalize_bbox(bbox, rows, cols) for bbox in bboxes]
python
def normalize_bboxes(bboxes, rows, cols): """Normalize a list of bounding boxes.""" return [normalize_bbox(bbox, rows, cols) for bbox in bboxes]
[ "def", "normalize_bboxes", "(", "bboxes", ",", "rows", ",", "cols", ")", ":", "return", "[", "normalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "for", "bbox", "in", "bboxes", "]" ]
Normalize a list of bounding boxes.
[ "Normalize", "a", "list", "of", "bounding", "boxes", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L37-L39
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
denormalize_bboxes
def denormalize_bboxes(bboxes, rows, cols): """Denormalize a list of bounding boxes.""" return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
python
def denormalize_bboxes(bboxes, rows, cols): """Denormalize a list of bounding boxes.""" return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
[ "def", "denormalize_bboxes", "(", "bboxes", ",", "rows", ",", "cols", ")", ":", "return", "[", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "for", "bbox", "in", "bboxes", "]" ]
Denormalize a list of bounding boxes.
[ "Denormalize", "a", "list", "of", "bounding", "boxes", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L42-L44
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
calculate_bbox_area
def calculate_bbox_area(bbox, rows, cols): """Calculate the area of a bounding box in pixels.""" bbox = denormalize_bbox(bbox, rows, cols) x_min, y_min, x_max, y_max = bbox[:4] area = (x_max - x_min) * (y_max - y_min) return area
python
def calculate_bbox_area(bbox, rows, cols): """Calculate the area of a bounding box in pixels.""" bbox = denormalize_bbox(bbox, rows, cols) x_min, y_min, x_max, y_max = bbox[:4] area = (x_max - x_min) * (y_max - y_min) return area
[ "def", "calculate_bbox_area", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "bbox", "=", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "[", ":", "4", "]", "area", ...
Calculate the area of a bounding box in pixels.
[ "Calculate", "the", "area", "of", "a", "bounding", "box", "in", "pixels", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L47-L52
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
filter_bboxes_by_visibility
def filter_bboxes_by_visibility(original_shape, bboxes, transformed_shape, transformed_bboxes, threshold=0., min_area=0.): """Filter bounding boxes and return only those boxes whose visibility after transformation is above the threshold and minimal area of bounding box in pixels ...
python
def filter_bboxes_by_visibility(original_shape, bboxes, transformed_shape, transformed_bboxes, threshold=0., min_area=0.): """Filter bounding boxes and return only those boxes whose visibility after transformation is above the threshold and minimal area of bounding box in pixels ...
[ "def", "filter_bboxes_by_visibility", "(", "original_shape", ",", "bboxes", ",", "transformed_shape", ",", "transformed_bboxes", ",", "threshold", "=", "0.", ",", "min_area", "=", "0.", ")", ":", "img_height", ",", "img_width", "=", "original_shape", "[", ":", "...
Filter bounding boxes and return only those boxes whose visibility after transformation is above the threshold and minimal area of bounding box in pixels is more then min_area. Args: original_shape (tuple): original image shape bboxes (list): original bounding boxes transformed_shape(tu...
[ "Filter", "bounding", "boxes", "and", "return", "only", "those", "boxes", "whose", "visibility", "after", "transformation", "is", "above", "the", "threshold", "and", "minimal", "area", "of", "bounding", "box", "in", "pixels", "is", "more", "then", "min_area", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L55-L82
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
convert_bbox_to_albumentations
def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False): """Convert a bounding box from a format specified in `source_format` to the format used by albumentations: normalized coordinates of bottom-left and top-right corners of the bounding box in a form of `[x_min, y_min, x...
python
def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False): """Convert a bounding box from a format specified in `source_format` to the format used by albumentations: normalized coordinates of bottom-left and top-right corners of the bounding box in a form of `[x_min, y_min, x...
[ "def", "convert_bbox_to_albumentations", "(", "bbox", ",", "source_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "if", "source_format", "not", "in", "{", "'coco'", ",", "'pascal_voc'", "}", ":", "raise", "ValueError", "(", ...
Convert a bounding box from a format specified in `source_format` to the format used by albumentations: normalized coordinates of bottom-left and top-right corners of the bounding box in a form of `[x_min, y_min, x_max, y_max]` e.g. `[0.15, 0.27, 0.67, 0.5]`. Args: bbox (list): bounding box ...
[ "Convert", "a", "bounding", "box", "from", "a", "format", "specified", "in", "source_format", "to", "the", "format", "used", "by", "albumentations", ":", "normalized", "coordinates", "of", "bottom", "-", "left", "and", "top", "-", "right", "corners", "of", "...
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L85-L119
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
convert_bbox_from_albumentations
def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False): """Convert a bounding box from the format used by albumentations to a format, specified in `target_format`. Args: bbox (list): bounding box with coordinates in the format used by albumentations target_f...
python
def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False): """Convert a bounding box from the format used by albumentations to a format, specified in `target_format`. Args: bbox (list): bounding box with coordinates in the format used by albumentations target_f...
[ "def", "convert_bbox_from_albumentations", "(", "bbox", ",", "target_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "if", "target_format", "not", "in", "{", "'coco'", ",", "'pascal_voc'", "}", ":", "raise", "ValueError", "(",...
Convert a bounding box from the format used by albumentations to a format, specified in `target_format`. Args: bbox (list): bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. r...
[ "Convert", "a", "bounding", "box", "from", "the", "format", "used", "by", "albumentations", "to", "a", "format", "specified", "in", "target_format", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L122-L152
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
convert_bboxes_to_albumentations
def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False): """Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations """ return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox...
python
def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False): """Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations """ return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox...
[ "def", "convert_bboxes_to_albumentations", "(", "bboxes", ",", "source_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "return", "[", "convert_bbox_to_albumentations", "(", "bbox", ",", "source_format", ",", "rows", ",", "cols", ...
Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations
[ "Convert", "a", "list", "bounding", "boxes", "from", "a", "format", "specified", "in", "source_format", "to", "the", "format", "used", "by", "albumentations" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L155-L158
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
convert_bboxes_from_albumentations
def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False): """Convert a list of bounding boxes from the format used by albumentations to a format, specified in `target_format`. Args: bboxes (list): List of bounding box with coordinates in the format used by alb...
python
def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False): """Convert a list of bounding boxes from the format used by albumentations to a format, specified in `target_format`. Args: bboxes (list): List of bounding box with coordinates in the format used by alb...
[ "def", "convert_bboxes_from_albumentations", "(", "bboxes", ",", "target_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "return", "[", "convert_bbox_from_albumentations", "(", "bbox", ",", "target_format", ",", "rows", ",", "cols...
Convert a list of bounding boxes from the format used by albumentations to a format, specified in `target_format`. Args: bboxes (list): List of bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or...
[ "Convert", "a", "list", "of", "bounding", "boxes", "from", "the", "format", "used", "by", "albumentations", "to", "a", "format", "specified", "in", "target_format", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L161-L172
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
check_bbox
def check_bbox(bbox): """Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums""" for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]): if not 0 <= value <= 1: raise ValueError( 'Expected {name} for bbox {bbox} ' 't...
python
def check_bbox(bbox): """Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums""" for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]): if not 0 <= value <= 1: raise ValueError( 'Expected {name} for bbox {bbox} ' 't...
[ "def", "check_bbox", "(", "bbox", ")", ":", "for", "name", ",", "value", "in", "zip", "(", "[", "'x_min'", ",", "'y_min'", ",", "'x_max'", ",", "'y_max'", "]", ",", "bbox", "[", ":", "4", "]", ")", ":", "if", "not", "0", "<=", "value", "<=", "1...
Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums
[ "Check", "if", "bbox", "boundaries", "are", "in", "range", "0", "1", "and", "minimums", "are", "lesser", "then", "maximums" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L175-L195
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
filter_bboxes
def filter_bboxes(bboxes, rows, cols, min_area=0., min_visibility=0.): """Remove bounding boxes that either lie outside of the visible area by more then min_visibility or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size. Args: bboxes (list): Lis...
python
def filter_bboxes(bboxes, rows, cols, min_area=0., min_visibility=0.): """Remove bounding boxes that either lie outside of the visible area by more then min_visibility or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size. Args: bboxes (list): Lis...
[ "def", "filter_bboxes", "(", "bboxes", ",", "rows", ",", "cols", ",", "min_area", "=", "0.", ",", "min_visibility", "=", "0.", ")", ":", "resulting_boxes", "=", "[", "]", "for", "bbox", "in", "bboxes", ":", "transformed_box_area", "=", "calculate_bbox_area",...
Remove bounding boxes that either lie outside of the visible area by more then min_visibility or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size. Args: bboxes (list): List of bounding box with coordinates in the format used by albumentations ...
[ "Remove", "bounding", "boxes", "that", "either", "lie", "outside", "of", "the", "visible", "area", "by", "more", "then", "min_visibility", "or", "whose", "area", "in", "pixels", "is", "under", "the", "threshold", "set", "by", "min_area", ".", "Also", "it", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L204-L228
train
albu/albumentations
albumentations/augmentations/bbox_utils.py
union_of_bboxes
def union_of_bboxes(height, width, bboxes, erosion_rate=0.0, to_int=False): """Calculate union of bounding boxes. Args: height (float): Height of image or space. width (float): Width of image or space. bboxes (list): List like bounding boxes. Format is `[x_min, y_min, x_max, y_max]`. ...
python
def union_of_bboxes(height, width, bboxes, erosion_rate=0.0, to_int=False): """Calculate union of bounding boxes. Args: height (float): Height of image or space. width (float): Width of image or space. bboxes (list): List like bounding boxes. Format is `[x_min, y_min, x_max, y_max]`. ...
[ "def", "union_of_bboxes", "(", "height", ",", "width", ",", "bboxes", ",", "erosion_rate", "=", "0.0", ",", "to_int", "=", "False", ")", ":", "x1", ",", "y1", "=", "width", ",", "height", "x2", ",", "y2", "=", "0", ",", "0", "for", "b", "in", "bb...
Calculate union of bounding boxes. Args: height (float): Height of image or space. width (float): Width of image or space. bboxes (list): List like bounding boxes. Format is `[x_min, y_min, x_max, y_max]`. erosion_rate (float): How much each bounding box can be shrinked, useful for ...
[ "Calculate", "union", "of", "bounding", "boxes", "." ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L231-L249
train
albu/albumentations
albumentations/core/transforms_interface.py
to_tuple
def to_tuple(param, low=None, bias=None): """Convert input argument to min-max tuple Args: param (scalar, tuple or list of 2+ elements): Input value. If value is scalar, return value would be (offset - value, offset + value). If value is tuple, return value would be value + offse...
python
def to_tuple(param, low=None, bias=None): """Convert input argument to min-max tuple Args: param (scalar, tuple or list of 2+ elements): Input value. If value is scalar, return value would be (offset - value, offset + value). If value is tuple, return value would be value + offse...
[ "def", "to_tuple", "(", "param", ",", "low", "=", "None", ",", "bias", "=", "None", ")", ":", "if", "low", "is", "not", "None", "and", "bias", "is", "not", "None", ":", "raise", "ValueError", "(", "'Arguments low and bias are mutually exclusive'", ")", "if...
Convert input argument to min-max tuple Args: param (scalar, tuple or list of 2+ elements): Input value. If value is scalar, return value would be (offset - value, offset + value). If value is tuple, return value would be value + offset (broadcasted). low: Second element of ...
[ "Convert", "input", "argument", "to", "min", "-", "max", "tuple", "Args", ":", "param", "(", "scalar", "tuple", "or", "list", "of", "2", "+", "elements", ")", ":", "Input", "value", ".", "If", "value", "is", "scalar", "return", "value", "would", "be", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/core/transforms_interface.py#L8-L36
train
albu/albumentations
albumentations/augmentations/keypoints_utils.py
check_keypoint
def check_keypoint(kp, rows, cols): """Check if keypoint coordinates are in range [0, 1)""" for name, value, size in zip(['x', 'y'], kp[:2], [cols, rows]): if not 0 <= value < size: raise ValueError( 'Expected {name} for keypoint {kp} ' 'to be in the range [0....
python
def check_keypoint(kp, rows, cols): """Check if keypoint coordinates are in range [0, 1)""" for name, value, size in zip(['x', 'y'], kp[:2], [cols, rows]): if not 0 <= value < size: raise ValueError( 'Expected {name} for keypoint {kp} ' 'to be in the range [0....
[ "def", "check_keypoint", "(", "kp", ",", "rows", ",", "cols", ")", ":", "for", "name", ",", "value", ",", "size", "in", "zip", "(", "[", "'x'", ",", "'y'", "]", ",", "kp", "[", ":", "2", "]", ",", "[", "cols", ",", "rows", "]", ")", ":", "i...
Check if keypoint coordinates are in range [0, 1)
[ "Check", "if", "keypoint", "coordinates", "are", "in", "range", "[", "0", "1", ")" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/keypoints_utils.py#L5-L17
train
albu/albumentations
albumentations/augmentations/keypoints_utils.py
check_keypoints
def check_keypoints(keypoints, rows, cols): """Check if keypoints boundaries are in range [0, 1)""" for kp in keypoints: check_keypoint(kp, rows, cols)
python
def check_keypoints(keypoints, rows, cols): """Check if keypoints boundaries are in range [0, 1)""" for kp in keypoints: check_keypoint(kp, rows, cols)
[ "def", "check_keypoints", "(", "keypoints", ",", "rows", ",", "cols", ")", ":", "for", "kp", "in", "keypoints", ":", "check_keypoint", "(", "kp", ",", "rows", ",", "cols", ")" ]
Check if keypoints boundaries are in range [0, 1)
[ "Check", "if", "keypoints", "boundaries", "are", "in", "range", "[", "0", "1", ")" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/keypoints_utils.py#L20-L23
train
tornadoweb/tornado
tornado/autoreload.py
start
def start(check_time: int = 500) -> None: """Begins watching source files for changes. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. """ io_loop = ioloop.IOLoop.current() if io_loop in _io_loops: return _io_loops[io_loop] = True...
python
def start(check_time: int = 500) -> None: """Begins watching source files for changes. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. """ io_loop = ioloop.IOLoop.current() if io_loop in _io_loops: return _io_loops[io_loop] = True...
[ "def", "start", "(", "check_time", ":", "int", "=", "500", ")", "->", "None", ":", "io_loop", "=", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "if", "io_loop", "in", "_io_loops", ":", "return", "_io_loops", "[", "io_loop", "]", "=", "True", "i...
Begins watching source files for changes. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed.
[ "Begins", "watching", "source", "files", "for", "changes", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/autoreload.py#L118-L133
train
tornadoweb/tornado
tornado/autoreload.py
main
def main() -> None: """Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper ...
python
def main() -> None: """Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper ...
[ "def", "main", "(", ")", "->", "None", ":", "# Remember that we were launched with autoreload as main.", "# The main module can be tricky; set the variables both in our globals", "# (which may be __main__) and the real importable version.", "import", "tornado", ".", "autoreload", "global...
Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper is similar to calling `...
[ "Command", "-", "line", "wrapper", "to", "re", "-", "run", "a", "script", "whenever", "its", "source", "changes", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/autoreload.py#L272-L358
train
tornadoweb/tornado
tornado/tcpclient.py
_Connector.split
def split( addrinfo: List[Tuple] ) -> Tuple[ List[Tuple[socket.AddressFamily, Tuple]], List[Tuple[socket.AddressFamily, Tuple]], ]: """Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo``...
python
def split( addrinfo: List[Tuple] ) -> Tuple[ List[Tuple[socket.AddressFamily, Tuple]], List[Tuple[socket.AddressFamily, Tuple]], ]: """Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo``...
[ "def", "split", "(", "addrinfo", ":", "List", "[", "Tuple", "]", ")", "->", "Tuple", "[", "List", "[", "Tuple", "[", "socket", ".", "AddressFamily", ",", "Tuple", "]", "]", ",", "List", "[", "Tuple", "[", "socket", ".", "AddressFamily", ",", "Tuple",...
Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-...
[ "Partition", "the", "addrinfo", "list", "by", "address", "family", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpclient.py#L81-L103
train
tornadoweb/tornado
tornado/tcpclient.py
TCPClient.connect
async def connect( self, host: str, port: int, af: socket.AddressFamily = socket.AF_UNSPEC, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, max_buffer_size: int = None, source_ip: str = None, source_port: int = None, timeout: Union[float...
python
async def connect( self, host: str, port: int, af: socket.AddressFamily = socket.AF_UNSPEC, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, max_buffer_size: int = None, source_ip: str = None, source_port: int = None, timeout: Union[float...
[ "async", "def", "connect", "(", "self", ",", "host", ":", "str", ",", "port", ":", "int", ",", "af", ":", "socket", ".", "AddressFamily", "=", "socket", ".", "AF_UNSPEC", ",", "ssl_options", ":", "Union", "[", "Dict", "[", "str", ",", "Any", "]", "...
Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). Using the ``source_ip`` kwarg, one can specify the source IP address to use when establishing the connection. In case the user needs to resolve and ...
[ "Connect", "to", "the", "given", "host", "and", "port", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpclient.py#L222-L296
train
tornadoweb/tornado
tornado/httpserver.py
HTTPServer.close_all_connections
async def close_all_connections(self) -> None: """Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop ac...
python
async def close_all_connections(self) -> None: """Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop ac...
[ "async", "def", "close_all_connections", "(", "self", ")", "->", "None", ":", "while", "self", ".", "_connections", ":", "# Peek at an arbitrary element of the set", "conn", "=", "next", "(", "iter", "(", "self", ".", "_connections", ")", ")", "await", "conn", ...
Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop accepting new connections, then ``await close_all_co...
[ "Close", "all", "open", "connections", "and", "asynchronously", "wait", "for", "them", "to", "finish", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpserver.py#L204-L221
train
tornadoweb/tornado
tornado/httpserver.py
_HTTPRequestContext._apply_xheaders
def _apply_xheaders(self, headers: httputil.HTTPHeaders) -> None: """Rewrite the ``remote_ip`` and ``protocol`` fields.""" # Squid uses X-Forwarded-For, others use X-Real-Ip ip = headers.get("X-Forwarded-For", self.remote_ip) # Skip trusted downstream hosts in X-Forwarded-For list ...
python
def _apply_xheaders(self, headers: httputil.HTTPHeaders) -> None: """Rewrite the ``remote_ip`` and ``protocol`` fields.""" # Squid uses X-Forwarded-For, others use X-Real-Ip ip = headers.get("X-Forwarded-For", self.remote_ip) # Skip trusted downstream hosts in X-Forwarded-For list ...
[ "def", "_apply_xheaders", "(", "self", ",", "headers", ":", "httputil", ".", "HTTPHeaders", ")", "->", "None", ":", "# Squid uses X-Forwarded-For, others use X-Real-Ip", "ip", "=", "headers", ".", "get", "(", "\"X-Forwarded-For\"", ",", "self", ".", "remote_ip", "...
Rewrite the ``remote_ip`` and ``protocol`` fields.
[ "Rewrite", "the", "remote_ip", "and", "protocol", "fields", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpserver.py#L332-L352
train
tornadoweb/tornado
tornado/httpserver.py
_HTTPRequestContext._unapply_xheaders
def _unapply_xheaders(self) -> None: """Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection. """ self.remote_ip = self._orig_remote_ip self.protocol = self._orig_protocol
python
def _unapply_xheaders(self) -> None: """Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection. """ self.remote_ip = self._orig_remote_ip self.protocol = self._orig_protocol
[ "def", "_unapply_xheaders", "(", "self", ")", "->", "None", ":", "self", ".", "remote_ip", "=", "self", ".", "_orig_remote_ip", "self", ".", "protocol", "=", "self", ".", "_orig_protocol" ]
Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection.
[ "Undo", "changes", "from", "_apply_xheaders", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpserver.py#L354-L361
train
tornadoweb/tornado
tornado/locale.py
set_default_locale
def set_default_locale(code: str) -> None: """Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a tran...
python
def set_default_locale(code: str) -> None: """Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a tran...
[ "def", "set_default_locale", "(", "code", ":", "str", ")", "->", "None", ":", "global", "_default_locale", "global", "_supported_locales", "_default_locale", "=", "code", "_supported_locales", "=", "frozenset", "(", "list", "(", "_translations", ".", "keys", "(", ...
Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a translation file for the default locale.
[ "Sets", "the", "default", "locale", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L77-L88
train
tornadoweb/tornado
tornado/locale.py
load_translations
def load_translations(directory: str, encoding: str = None) -> None: """Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation file...
python
def load_translations(directory: str, encoding: str = None) -> None: """Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation file...
[ "def", "load_translations", "(", "directory", ":", "str", ",", "encoding", ":", "str", "=", "None", ")", "->", "None", ":", "global", "_translations", "global", "_supported_locales", "_translations", "=", "{", "}", "for", "path", "in", "os", ".", "listdir", ...
Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should h...
[ "Loads", "translations", "from", "CSV", "files", "in", "a", "directory", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L91-L175
train
tornadoweb/tornado
tornado/locale.py
load_gettext_translations
def load_gettext_translations(directory: str, domain: str) -> None: """Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate...
python
def load_gettext_translations(directory: str, domain: str) -> None: """Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate...
[ "def", "load_gettext_translations", "(", "directory", ":", "str", ",", "domain", ":", "str", ")", "->", "None", ":", "global", "_translations", "global", "_supported_locales", "global", "_use_gettext", "_translations", "=", "{", "}", "for", "lang", "in", "os", ...
Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Python --keyword=_:1,2...
[ "Loads", "translations", "from", "gettext", "s", "locale", "tree" ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L178-L218
train
tornadoweb/tornado
tornado/locale.py
Locale.get_closest
def get_closest(cls, *locale_codes: str) -> "Locale": """Returns the closest match for the given locale code.""" for code in locale_codes: if not code: continue code = code.replace("-", "_") parts = code.split("_") if len(parts) > 2: ...
python
def get_closest(cls, *locale_codes: str) -> "Locale": """Returns the closest match for the given locale code.""" for code in locale_codes: if not code: continue code = code.replace("-", "_") parts = code.split("_") if len(parts) > 2: ...
[ "def", "get_closest", "(", "cls", ",", "*", "locale_codes", ":", "str", ")", "->", "\"Locale\"", ":", "for", "code", "in", "locale_codes", ":", "if", "not", "code", ":", "continue", "code", "=", "code", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", ...
Returns the closest match for the given locale code.
[ "Returns", "the", "closest", "match", "for", "the", "given", "locale", "code", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L236-L251
train
tornadoweb/tornado
tornado/locale.py
Locale.get
def get(cls, code: str) -> "Locale": """Returns the Locale for the given locale code. If it is not supported, we raise an exception. """ if code not in cls._cache: assert code in _supported_locales translations = _translations.get(code, None) if trans...
python
def get(cls, code: str) -> "Locale": """Returns the Locale for the given locale code. If it is not supported, we raise an exception. """ if code not in cls._cache: assert code in _supported_locales translations = _translations.get(code, None) if trans...
[ "def", "get", "(", "cls", ",", "code", ":", "str", ")", "->", "\"Locale\"", ":", "if", "code", "not", "in", "cls", ".", "_cache", ":", "assert", "code", "in", "_supported_locales", "translations", "=", "_translations", ".", "get", "(", "code", ",", "No...
Returns the Locale for the given locale code. If it is not supported, we raise an exception.
[ "Returns", "the", "Locale", "for", "the", "given", "locale", "code", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L254-L269
train
tornadoweb/tornado
tornado/locale.py
Locale.translate
def translate( self, message: str, plural_message: str = None, count: int = None ) -> str: """Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and...
python
def translate( self, message: str, plural_message: str = None, count: int = None ) -> str: """Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and...
[ "def", "translate", "(", "self", ",", "message", ":", "str", ",", "plural_message", ":", "str", "=", "None", ",", "count", ":", "int", "=", "None", ")", "->", "str", ":", "raise", "NotImplementedError", "(", ")" ]
Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and we return the singular form for the given message when ``count == 1``.
[ "Returns", "the", "translation", "for", "the", "given", "message", "for", "this", "locale", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L306-L316
train
tornadoweb/tornado
tornado/locale.py
Locale.format_date
def format_date( self, date: Union[int, float, datetime.datetime], gmt_offset: int = 0, relative: bool = True, shorter: bool = False, full_format: bool = False, ) -> str: """Formats the given date (which should be GMT). By default, we return a relativ...
python
def format_date( self, date: Union[int, float, datetime.datetime], gmt_offset: int = 0, relative: bool = True, shorter: bool = False, full_format: bool = False, ) -> str: """Formats the given date (which should be GMT). By default, we return a relativ...
[ "def", "format_date", "(", "self", ",", "date", ":", "Union", "[", "int", ",", "float", ",", "datetime", ".", "datetime", "]", ",", "gmt_offset", ":", "int", "=", "0", ",", "relative", ":", "bool", "=", "True", ",", "shorter", ":", "bool", "=", "Fa...
Formats the given date (which should be GMT). By default, we return a relative time (e.g., "2 minutes ago"). You can return an absolute date string with ``relative=False``. You can force a full format date ("July 10, 1980") with ``full_format=True``. This method is primarily i...
[ "Formats", "the", "given", "date", "(", "which", "should", "be", "GMT", ")", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L323-L421
train
tornadoweb/tornado
tornado/locale.py
Locale.format_day
def format_day( self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True ) -> bool: """Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``. """ local_date = date - datetime.timedelta(mi...
python
def format_day( self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True ) -> bool: """Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``. """ local_date = date - datetime.timedelta(mi...
[ "def", "format_day", "(", "self", ",", "date", ":", "datetime", ".", "datetime", ",", "gmt_offset", ":", "int", "=", "0", ",", "dow", ":", "bool", "=", "True", ")", "->", "bool", ":", "local_date", "=", "date", "-", "datetime", ".", "timedelta", "(",...
Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``.
[ "Formats", "the", "given", "date", "as", "a", "day", "of", "week", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L423-L443
train
tornadoweb/tornado
tornado/locale.py
Locale.list
def list(self, parts: Any) -> str: """Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1. """ _ = self.translate if len(parts) == 0: return "" if len(parts) == 1: ...
python
def list(self, parts: Any) -> str: """Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1. """ _ = self.translate if len(parts) == 0: return "" if len(parts) == 1: ...
[ "def", "list", "(", "self", ",", "parts", ":", "Any", ")", "->", "str", ":", "_", "=", "self", ".", "translate", "if", "len", "(", "parts", ")", "==", "0", ":", "return", "\"\"", "if", "len", "(", "parts", ")", "==", "1", ":", "return", "parts"...
Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1.
[ "Returns", "a", "comma", "-", "separated", "list", "for", "the", "given", "list", "of", "parts", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L445-L460
train
tornadoweb/tornado
tornado/locale.py
Locale.friendly_number
def friendly_number(self, value: int) -> str: """Returns a comma-separated number for the given integer.""" if self.code not in ("en", "en_US"): return str(value) s = str(value) parts = [] while s: parts.append(s[-3:]) s = s[:-3] return...
python
def friendly_number(self, value: int) -> str: """Returns a comma-separated number for the given integer.""" if self.code not in ("en", "en_US"): return str(value) s = str(value) parts = [] while s: parts.append(s[-3:]) s = s[:-3] return...
[ "def", "friendly_number", "(", "self", ",", "value", ":", "int", ")", "->", "str", ":", "if", "self", ".", "code", "not", "in", "(", "\"en\"", ",", "\"en_US\"", ")", ":", "return", "str", "(", "value", ")", "s", "=", "str", "(", "value", ")", "pa...
Returns a comma-separated number for the given integer.
[ "Returns", "a", "comma", "-", "separated", "number", "for", "the", "given", "integer", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L462-L471
train
tornadoweb/tornado
tornado/locale.py
GettextLocale.pgettext
def pgettext( self, context: str, message: str, plural_message: str = None, count: int = None ) -> str: """Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example...
python
def pgettext( self, context: str, message: str, plural_message: str = None, count: int = None ) -> str: """Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example...
[ "def", "pgettext", "(", "self", ",", "context", ":", "str", ",", "message", ":", "str", ",", "plural_message", ":", "str", "=", "None", ",", "count", ":", "int", "=", "None", ")", "->", "str", ":", "if", "plural_message", "is", "not", "None", ":", ...
Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example:: pgettext("organization", "club", "clubs", len(clubs)) pgettext("stick", "club", "clubs", len(clubs)...
[ "Allows", "to", "set", "context", "for", "translation", "accepts", "plural", "forms", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L522-L562
train
tornadoweb/tornado
tornado/routing.py
_unquote_or_none
def _unquote_or_none(s: Optional[str]) -> Optional[bytes]: # noqa: F811 """None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use. """ if s is None: return s return url_u...
python
def _unquote_or_none(s: Optional[str]) -> Optional[bytes]: # noqa: F811 """None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use. """ if s is None: return s return url_u...
[ "def", "_unquote_or_none", "(", "s", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "bytes", "]", ":", "# noqa: F811", "if", "s", "is", "None", ":", "return", "s", "return", "url_unescape", "(", "s", ",", "encoding", "=", "None", ",", ...
None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use.
[ "None", "-", "safe", "wrapper", "around", "url_unescape", "to", "handle", "unmatched", "optional", "groups", "correctly", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L702-L711
train
tornadoweb/tornado
tornado/routing.py
Router.find_handler
def find_handler( self, request: httputil.HTTPServerRequest, **kwargs: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional...
python
def find_handler( self, request: httputil.HTTPServerRequest, **kwargs: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional...
[ "def", "find_handler", "(", "self", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Optional", "[", "httputil", ".", "HTTPMessageDelegate", "]", ":", "raise", "NotImplementedError", "(", ")" ]
Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional kwargs to extend the routing logic. :arg httputil.HTTPServerRequest request: current HTTP request. :arg kwargs: additional ke...
[ "Must", "be", "implemented", "to", "return", "an", "appropriate", "instance", "of", "~", ".", "httputil", ".", "HTTPMessageDelegate", "that", "can", "serve", "the", "request", ".", "Routing", "implementations", "may", "pass", "additional", "kwargs", "to", "exten...
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L193-L205
train
tornadoweb/tornado
tornado/routing.py
RuleRouter.add_rules
def add_rules(self, rules: _RuleList) -> None: """Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor). """ for rule in rules: if isinstance(rule, (tuple, list)): asse...
python
def add_rules(self, rules: _RuleList) -> None: """Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor). """ for rule in rules: if isinstance(rule, (tuple, list)): asse...
[ "def", "add_rules", "(", "self", ",", "rules", ":", "_RuleList", ")", "->", "None", ":", "for", "rule", "in", "rules", ":", "if", "isinstance", "(", "rule", ",", "(", "tuple", ",", "list", ")", ")", ":", "assert", "len", "(", "rule", ")", "in", "...
Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor).
[ "Appends", "new", "rules", "to", "the", "router", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L334-L348
train
tornadoweb/tornado
tornado/routing.py
RuleRouter.get_target_delegate
def get_target_delegate( self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be exte...
python
def get_target_delegate( self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be exte...
[ "def", "get_target_delegate", "(", "self", ",", "target", ":", "Any", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ",", "*", "*", "target_params", ":", "Any", ")", "->", "Optional", "[", "httputil", ".", "HTTPMessageDelegate", "]", ":", "if", ...
Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be extended to provide additional target types. :arg target: a Rule's target. :arg httputil.HTTPServerRequest request: current request. :arg target_para...
[ "Returns", "an", "instance", "of", "~", ".", "httputil", ".", "HTTPMessageDelegate", "for", "a", "Rule", "s", "target", ".", "This", "method", "is", "called", "by", "~", ".", "find_handler", "and", "can", "be", "extended", "to", "provide", "additional", "t...
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L376-L401
train
tornadoweb/tornado
tornado/routing.py
Matcher.match
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]: """Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_...
python
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]: """Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_...
[ "def", "match", "(", "self", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "raise", "NotImplementedError", "(", ")" ]
Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs`` can be passed for proper `~.web.RequestH...
[ "Matches", "current", "instance", "against", "the", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L493-L503
train
tornadoweb/tornado
tornado/routing.py
PathMatches._find_groups
def _find_groups(self) -> Tuple[Optional[str], Optional[int]]: """Returns a tuple (reverse string, group count) for a url. For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method would return ('/%s/%s/', 2). """ pattern = self.regex.pattern if pattern.star...
python
def _find_groups(self) -> Tuple[Optional[str], Optional[int]]: """Returns a tuple (reverse string, group count) for a url. For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method would return ('/%s/%s/', 2). """ pattern = self.regex.pattern if pattern.star...
[ "def", "_find_groups", "(", "self", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "Optional", "[", "int", "]", "]", ":", "pattern", "=", "self", ".", "regex", ".", "pattern", "if", "pattern", ".", "startswith", "(", "\"^\"", ")", ":", ...
Returns a tuple (reverse string, group count) for a url. For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method would return ('/%s/%s/', 2).
[ "Returns", "a", "tuple", "(", "reverse", "string", "group", "count", ")", "for", "a", "url", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L608-L640
train
tornadoweb/tornado
demos/webspider/webspider.py
get_links_from_url
async def get_links_from_url(url): """Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes 'http://www.tornadoweb.org/en/stable/gen.html'. """ response = a...
python
async def get_links_from_url(url): """Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes 'http://www.tornadoweb.org/en/stable/gen.html'. """ response = a...
[ "async", "def", "get_links_from_url", "(", "url", ")", ":", "response", "=", "await", "httpclient", ".", "AsyncHTTPClient", "(", ")", ".", "fetch", "(", "url", ")", "print", "(", "\"fetched %s\"", "%", "url", ")", "html", "=", "response", ".", "body", "....
Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes 'http://www.tornadoweb.org/en/stable/gen.html'.
[ "Download", "the", "page", "at", "url", "and", "parse", "it", "for", "links", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/webspider/webspider.py#L15-L26
train
tornadoweb/tornado
demos/chat/chatdemo.py
MessageBuffer.get_messages_since
def get_messages_since(self, cursor): """Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received. """ results = [] for msg in reversed(self.cache): if msg["id"] == cursor: break ...
python
def get_messages_since(self, cursor): """Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received. """ results = [] for msg in reversed(self.cache): if msg["id"] == cursor: break ...
[ "def", "get_messages_since", "(", "self", ",", "cursor", ")", ":", "results", "=", "[", "]", "for", "msg", "in", "reversed", "(", "self", ".", "cache", ")", ":", "if", "msg", "[", "\"id\"", "]", "==", "cursor", ":", "break", "results", ".", "append",...
Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received.
[ "Returns", "a", "list", "of", "messages", "newer", "than", "the", "given", "cursor", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/chat/chatdemo.py#L38-L49
train
tornadoweb/tornado
tornado/util.py
import_object
def import_object(name: str) -> Any: """Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object...
python
def import_object(name: str) -> Any: """Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object...
[ "def", "import_object", "(", "name", ":", "str", ")", "->", "Any", ":", "if", "name", ".", "count", "(", "\".\"", ")", "==", "0", ":", "return", "__import__", "(", "name", ")", "parts", "=", "name", ".", "split", "(", "\".\"", ")", "obj", "=", "_...
Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.ut...
[ "Imports", "an", "object", "by", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L131-L157
train
tornadoweb/tornado
tornado/util.py
errno_from_exception
def errno_from_exception(e: BaseException) -> Optional[int]: """Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function ...
python
def errno_from_exception(e: BaseException) -> Optional[int]: """Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function ...
[ "def", "errno_from_exception", "(", "e", ":", "BaseException", ")", "->", "Optional", "[", "int", "]", ":", "if", "hasattr", "(", "e", ",", "\"errno\"", ")", ":", "return", "e", ".", "errno", "# type: ignore", "elif", "e", ".", "args", ":", "return", "...
Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to give you a safe way to get the ...
[ "Provides", "the", "errno", "from", "an", "Exception", "object", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L188-L203
train
tornadoweb/tornado
tornado/util.py
_websocket_mask_python
def _websocket_mask_python(mask: bytes, data: bytes) -> bytes: """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This ...
python
def _websocket_mask_python(mask: bytes, data: bytes) -> bytes: """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This ...
[ "def", "_websocket_mask_python", "(", "mask", ":", "bytes", ",", "data", ":", "bytes", ")", "->", "bytes", ":", "mask_arr", "=", "array", ".", "array", "(", "\"B\"", ",", "mask", ")", "unmasked_arr", "=", "array", ".", "array", "(", "\"B\"", ",", "data...
Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version whe...
[ "Websocket", "masking", "function", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L439-L452
train
tornadoweb/tornado
tornado/util.py
GzipDecompressor.decompress
def decompress(self, value: bytes, max_length: int = 0) -> bytes: """Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_lengt...
python
def decompress(self, value: bytes, max_length: int = 0) -> bytes: """Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_lengt...
[ "def", "decompress", "(", "self", ",", "value", ":", "bytes", ",", "max_length", ":", "int", "=", "0", ")", "->", "bytes", ":", "return", "self", ".", "decompressobj", ".", "decompress", "(", "value", ",", "max_length", ")" ]
Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_length`` is given, some input data may be left over in ``unconsumed_tail``...
[ "Decompress", "a", "chunk", "returning", "newly", "-", "available", "data", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L103-L114
train
tornadoweb/tornado
tornado/util.py
Configurable.configure
def configure(cls, impl, **kwargs): # type: (Union[None, str, Type[Configurable]], Any) -> None """Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults fo...
python
def configure(cls, impl, **kwargs): # type: (Union[None, str, Type[Configurable]], Any) -> None """Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults fo...
[ "def", "configure", "(", "cls", ",", "impl", ",", "*", "*", "kwargs", ")", ":", "# type: (Union[None, str, Type[Configurable]], Any) -> None", "base", "=", "cls", ".", "configurable_base", "(", ")", "if", "isinstance", "(", "impl", ",", "str", ")", ":", "impl"...
Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters.
[ "Sets", "the", "class", "to", "use", "when", "the", "base", "class", "is", "instantiated", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L320-L334
train
tornadoweb/tornado
tornado/util.py
ArgReplacer.get_old_value
def get_old_value( self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None ) -> Any: """Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present. """ if self.arg_pos is not None and len(args) > self.a...
python
def get_old_value( self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None ) -> Any: """Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present. """ if self.arg_pos is not None and len(args) > self.a...
[ "def", "get_old_value", "(", "self", ",", "args", ":", "Sequence", "[", "Any", "]", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ",", "default", ":", "Any", "=", "None", ")", "->", "Any", ":", "if", "self", ".", "arg_pos", "is", "not"...
Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present.
[ "Returns", "the", "old", "value", "of", "the", "named", "argument", "without", "replacing", "it", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L397-L407
train
tornadoweb/tornado
tornado/util.py
ArgReplacer.replace
def replace( self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any] ) -> Tuple[Any, Sequence[Any], Dict[str, Any]]: """Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects m...
python
def replace( self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any] ) -> Tuple[Any, Sequence[Any], Dict[str, Any]]: """Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects m...
[ "def", "replace", "(", "self", ",", "new_value", ":", "Any", ",", "args", ":", "Sequence", "[", "Any", "]", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "Any", ",", "Sequence", "[", "Any", "]", ",", "Dict", ...
Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects may not be the same as the input objects, or the input objects may be mutated. If the named argument was not found, ``new_value`` will...
[ "Replace", "the", "named", "argument", "in", "args", "kwargs", "with", "new_value", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L409-L430
train
tornadoweb/tornado
tornado/wsgi.py
WSGIContainer.environ
def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]: """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. """ hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: ...
python
def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]: """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. """ hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: ...
[ "def", "environ", "(", "request", ":", "httputil", ".", "HTTPServerRequest", ")", "->", "Dict", "[", "Text", ",", "Any", "]", ":", "hostport", "=", "request", ".", "host", ".", "split", "(", "\":\"", ")", "if", "len", "(", "hostport", ")", "==", "2",...
Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
[ "Converts", "a", "tornado", ".", "httputil", ".", "HTTPServerRequest", "to", "a", "WSGI", "environment", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/wsgi.py#L148-L183
train
tornadoweb/tornado
tornado/web.py
stream_request_body
def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]: """Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get...
python
def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]: """Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get...
[ "def", "stream_request_body", "(", "cls", ":", "Type", "[", "RequestHandler", "]", ")", "->", "Type", "[", "RequestHandler", "]", ":", "# noqa: E501", "if", "not", "issubclass", "(", "cls", ",", "RequestHandler", ")", ":", "raise", "TypeError", "(", "\"expec...
Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have ...
[ "Apply", "to", "RequestHandler", "subclasses", "to", "enable", "streaming", "body", "support", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1824-L1848
train
tornadoweb/tornado
tornado/web.py
removeslash
def removeslash( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping shoul...
python
def removeslash( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping shoul...
[ "def", "removeslash", "(", "method", ":", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ")", "->", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ":", "@", "functools", ...
Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping should use a regular expression like ``r'/foo/*'`` in conjunction with using the decorator.
[ "Use", "this", "decorator", "to", "remove", "trailing", "slashes", "from", "the", "request", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1857-L1883
train
tornadoweb/tornado
tornado/web.py
authenticated
def authenticated( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. ...
python
def authenticated( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. ...
[ "def", "authenticated", "(", "method", ":", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ")", "->", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ":", "@", "functools"...
Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. I...
[ "Decorate", "methods", "with", "this", "to", "require", "that", "the", "user", "be", "logged", "in", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L3142-L3176
train
tornadoweb/tornado
tornado/web.py
RequestHandler.on_connection_close
def on_connection_close(self) -> None: """Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you ...
python
def on_connection_close(self) -> None: """Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you ...
[ "def", "on_connection_close", "(", "self", ")", "->", "None", ":", "if", "_has_stream_request_body", "(", "self", ".", "__class__", ")", ":", "if", "not", "self", ".", "request", ".", "_body_future", ".", "done", "(", ")", ":", "self", ".", "request", "....
Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request over...
[ "Called", "in", "async", "handlers", "if", "the", "client", "closed", "the", "connection", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L300-L317
train
tornadoweb/tornado
tornado/web.py
RequestHandler.clear
def clear(self) -> None: """Resets all headers and content for this response.""" self._headers = httputil.HTTPHeaders( { "Server": "TornadoServer/%s" % tornado.version, "Content-Type": "text/html; charset=UTF-8", "Date": httputil.format_timesta...
python
def clear(self) -> None: """Resets all headers and content for this response.""" self._headers = httputil.HTTPHeaders( { "Server": "TornadoServer/%s" % tornado.version, "Content-Type": "text/html; charset=UTF-8", "Date": httputil.format_timesta...
[ "def", "clear", "(", "self", ")", "->", "None", ":", "self", ".", "_headers", "=", "httputil", ".", "HTTPHeaders", "(", "{", "\"Server\"", ":", "\"TornadoServer/%s\"", "%", "tornado", ".", "version", ",", "\"Content-Type\"", ":", "\"text/html; charset=UTF-8\"", ...
Resets all headers and content for this response.
[ "Resets", "all", "headers", "and", "content", "for", "this", "response", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L319-L331
train
tornadoweb/tornado
tornado/web.py
RequestHandler.set_status
def set_status(self, status_code: int, reason: str = None) -> None: """Sets the status code for our response. :arg int status_code: Response status code. :arg str reason: Human-readable reason phrase describing the status code. If ``None``, it will be filled in from `htt...
python
def set_status(self, status_code: int, reason: str = None) -> None: """Sets the status code for our response. :arg int status_code: Response status code. :arg str reason: Human-readable reason phrase describing the status code. If ``None``, it will be filled in from `htt...
[ "def", "set_status", "(", "self", ",", "status_code", ":", "int", ",", "reason", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "_status_code", "=", "status_code", "if", "reason", "is", "not", "None", ":", "self", ".", "_reason", "=", ...
Sets the status code for our response. :arg int status_code: Response status code. :arg str reason: Human-readable reason phrase describing the status code. If ``None``, it will be filled in from `http.client.responses` or "Unknown". .. versionchanged:: 5.0 ...
[ "Sets", "the", "status", "code", "for", "our", "response", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L343-L360
train
tornadoweb/tornado
tornado/web.py
RequestHandler.set_header
def set_header(self, name: str, value: _HeaderTypes) -> None: """Sets the given response header name and value. All header values are converted to strings (`datetime` objects are formatted according to the HTTP specification for the ``Date`` header). """ self._headers[n...
python
def set_header(self, name: str, value: _HeaderTypes) -> None: """Sets the given response header name and value. All header values are converted to strings (`datetime` objects are formatted according to the HTTP specification for the ``Date`` header). """ self._headers[n...
[ "def", "set_header", "(", "self", ",", "name", ":", "str", ",", "value", ":", "_HeaderTypes", ")", "->", "None", ":", "self", ".", "_headers", "[", "name", "]", "=", "self", ".", "_convert_header_value", "(", "value", ")" ]
Sets the given response header name and value. All header values are converted to strings (`datetime` objects are formatted according to the HTTP specification for the ``Date`` header).
[ "Sets", "the", "given", "response", "header", "name", "and", "value", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L366-L374
train
tornadoweb/tornado
tornado/web.py
RequestHandler.add_header
def add_header(self, name: str, value: _HeaderTypes) -> None: """Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times to return multiple values for the same header. """ self._headers.add(name, self._convert_header_value(value))
python
def add_header(self, name: str, value: _HeaderTypes) -> None: """Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times to return multiple values for the same header. """ self._headers.add(name, self._convert_header_value(value))
[ "def", "add_header", "(", "self", ",", "name", ":", "str", ",", "value", ":", "_HeaderTypes", ")", "->", "None", ":", "self", ".", "_headers", ".", "add", "(", "name", ",", "self", ".", "_convert_header_value", "(", "value", ")", ")" ]
Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times to return multiple values for the same header.
[ "Adds", "the", "given", "response", "header", "and", "value", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L376-L382
train
tornadoweb/tornado
tornado/web.py
RequestHandler.clear_header
def clear_header(self, name: str) -> None: """Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`. """ if name in self._headers: del self._headers[name]
python
def clear_header(self, name: str) -> None: """Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`. """ if name in self._headers: del self._headers[name]
[ "def", "clear_header", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "if", "name", "in", "self", ".", "_headers", ":", "del", "self", ".", "_headers", "[", "name", "]" ]
Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`.
[ "Clears", "an", "outgoing", "header", "undoing", "a", "previous", "set_header", "call", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L384-L391
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_argument
def get_argument( # noqa: F811 self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name. If default is not provided, the argument is considered to b...
python
def get_argument( # noqa: F811 self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name. If default is not provided, the argument is considered to b...
[ "def", "get_argument", "(", "# noqa: F811", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", ...
Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the request more than once, we return the last value. This method se...
[ "Returns", "the", "value", "of", "the", "argument", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L439-L455
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_arguments
def get_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. This method searches both the query and body arguments. """ # Make sure `get_arguments` isn't acc...
python
def get_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. This method searches both the query and body arguments. """ # Make sure `get_arguments` isn't acc...
[ "def", "get_arguments", "(", "self", ",", "name", ":", "str", ",", "strip", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "# Make sure `get_arguments` isn't accidentally being called with a", "# positional argument that's assumed to be a default (like...
Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. This method searches both the query and body arguments.
[ "Returns", "a", "list", "of", "the", "arguments", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L457-L470
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_body_argument
def get_body_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request body. If default is not provided, the argume...
python
def get_body_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request body. If default is not provided, the argume...
[ "def", "get_body_argument", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", "[", "str",...
Returns the value of the argument with the given name from the request body. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last valu...
[ "Returns", "the", "value", "of", "the", "argument", "with", "the", "given", "name", "from", "the", "request", "body", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L472-L489
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_body_arguments
def get_body_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the body arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.body_arguments, ...
python
def get_body_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the body arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.body_arguments, ...
[ "def", "get_body_arguments", "(", "self", ",", "name", ":", "str", ",", "strip", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "return", "self", ".", "_get_arguments", "(", "name", ",", "self", ".", "request", ".", "body_arguments"...
Returns a list of the body arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2
[ "Returns", "a", "list", "of", "the", "body", "arguments", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L491-L498
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_query_argument
def get_query_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request query string. If default is not provided, t...
python
def get_query_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request query string. If default is not provided, t...
[ "def", "get_query_argument", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", "[", "str"...
Returns the value of the argument with the given name from the request query string. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the l...
[ "Returns", "the", "value", "of", "the", "argument", "with", "the", "given", "name", "from", "the", "request", "query", "string", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L500-L517
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_query_arguments
def get_query_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the query arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.query_argument...
python
def get_query_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the query arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.query_argument...
[ "def", "get_query_arguments", "(", "self", ",", "name", ":", "str", ",", "strip", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "return", "self", ".", "_get_arguments", "(", "name", ",", "self", ".", "request", ".", "query_argument...
Returns a list of the query arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2
[ "Returns", "a", "list", "of", "the", "query", "arguments", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L519-L526
train
tornadoweb/tornado
tornado/web.py
RequestHandler.decode_argument
def decode_argument(self, value: bytes, name: str = None) -> str: """Decodes an argument from the request. The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in su...
python
def decode_argument(self, value: bytes, name: str = None) -> str: """Decodes an argument from the request. The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in su...
[ "def", "decode_argument", "(", "self", ",", "value", ":", "bytes", ",", "name", ":", "str", "=", "None", ")", "->", "str", ":", "try", ":", "return", "_unicode", "(", "value", ")", "except", "UnicodeDecodeError", ":", "raise", "HTTPError", "(", "400", ...
Decodes an argument from the request. The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses. This method is used as a filter for both `get_argument()` ...
[ "Decodes", "an", "argument", "from", "the", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L557-L575
train
tornadoweb/tornado
tornado/web.py
RequestHandler.cookies
def cookies(self) -> Dict[str, http.cookies.Morsel]: """An alias for `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.""" return self.request.cookies
python
def cookies(self) -> Dict[str, http.cookies.Morsel]: """An alias for `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.""" return self.request.cookies
[ "def", "cookies", "(", "self", ")", "->", "Dict", "[", "str", ",", "http", ".", "cookies", ".", "Morsel", "]", ":", "return", "self", ".", "request", ".", "cookies" ]
An alias for `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.
[ "An", "alias", "for", "self", ".", "request", ".", "cookies", "<", ".", "httputil", ".", "HTTPServerRequest", ".", "cookies", ">", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L578-L581
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_cookie
def get_cookie(self, name: str, default: str = None) -> Optional[str]: """Returns the value of the request cookie with the given name. If the named cookie is not present, returns ``default``. This method only returns cookies that were present in the request. It does not see the outgoin...
python
def get_cookie(self, name: str, default: str = None) -> Optional[str]: """Returns the value of the request cookie with the given name. If the named cookie is not present, returns ``default``. This method only returns cookies that were present in the request. It does not see the outgoin...
[ "def", "get_cookie", "(", "self", ",", "name", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "request", ".", "cookies", "is", "not", "None", "and", "name", "in", "self", ".", ...
Returns the value of the request cookie with the given name. If the named cookie is not present, returns ``default``. This method only returns cookies that were present in the request. It does not see the outgoing cookies set by `set_cookie` in this handler.
[ "Returns", "the", "value", "of", "the", "request", "cookie", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L583-L594
train
tornadoweb/tornado
tornado/web.py
RequestHandler.set_cookie
def set_cookie( self, name: str, value: Union[str, bytes], domain: str = None, expires: Union[float, Tuple, datetime.datetime] = None, path: str = "/", expires_days: int = None, **kwargs: Any ) -> None: """Sets an outgoing cookie name/value wit...
python
def set_cookie( self, name: str, value: Union[str, bytes], domain: str = None, expires: Union[float, Tuple, datetime.datetime] = None, path: str = "/", expires_days: int = None, **kwargs: Any ) -> None: """Sets an outgoing cookie name/value wit...
[ "def", "set_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "domain", ":", "str", "=", "None", ",", "expires", ":", "Union", "[", "float", ",", "Tuple", ",", "datetime", ".", "datetime"...
Sets an outgoing cookie name/value with the given options. Newly-set cookies are not immediately visible via `get_cookie`; they are not present until the next request. expires may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a ...
[ "Sets", "an", "outgoing", "cookie", "name", "/", "value", "with", "the", "given", "options", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L596-L649
train
tornadoweb/tornado
tornado/web.py
RequestHandler.clear_cookie
def clear_cookie(self, name: str, path: str = "/", domain: str = None) -> None: """Deletes the cookie with the given name. Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to fi...
python
def clear_cookie(self, name: str, path: str = "/", domain: str = None) -> None: """Deletes the cookie with the given name. Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to fi...
[ "def", "clear_cookie", "(", "self", ",", "name", ":", "str", ",", "path", ":", "str", "=", "\"/\"", ",", "domain", ":", "str", "=", "None", ")", "->", "None", ":", "expires", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "-", "datetime...
Deletes the cookie with the given name. Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie). Simi...
[ "Deletes", "the", "cookie", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L651-L663
train
tornadoweb/tornado
tornado/web.py
RequestHandler.clear_all_cookies
def clear_all_cookies(self, path: str = "/", domain: str = None) -> None: """Deletes all the cookies the user sent with this request. See `clear_cookie` for more information on the path and domain parameters. Similar to `set_cookie`, the effect of this method will not be seen u...
python
def clear_all_cookies(self, path: str = "/", domain: str = None) -> None: """Deletes all the cookies the user sent with this request. See `clear_cookie` for more information on the path and domain parameters. Similar to `set_cookie`, the effect of this method will not be seen u...
[ "def", "clear_all_cookies", "(", "self", ",", "path", ":", "str", "=", "\"/\"", ",", "domain", ":", "str", "=", "None", ")", "->", "None", ":", "for", "name", "in", "self", ".", "request", ".", "cookies", ":", "self", ".", "clear_cookie", "(", "name"...
Deletes all the cookies the user sent with this request. See `clear_cookie` for more information on the path and domain parameters. Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2 Added the ``...
[ "Deletes", "all", "the", "cookies", "the", "user", "sent", "with", "this", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L665-L679
train
tornadoweb/tornado
tornado/web.py
RequestHandler.set_secure_cookie
def set_secure_cookie( self, name: str, value: Union[str, bytes], expires_days: int = 30, version: int = None, **kwargs: Any ) -> None: """Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your App...
python
def set_secure_cookie( self, name: str, value: Union[str, bytes], expires_days: int = 30, version: int = None, **kwargs: Any ) -> None: """Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your App...
[ "def", "set_secure_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "expires_days", ":", "int", "=", "30", ",", "version", ":", "int", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ...
Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. To read a cookie set with this method, use `get_se...
[ "Signs", "and", "timestamps", "a", "cookie", "so", "it", "cannot", "be", "forged", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L681-L717
train
tornadoweb/tornado
tornado/web.py
RequestHandler.create_signed_value
def create_signed_value( self, name: str, value: Union[str, bytes], version: int = None ) -> bytes: """Signs and timestamps a string so it cannot be forged. Normally used via set_secure_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored ...
python
def create_signed_value( self, name: str, value: Union[str, bytes], version: int = None ) -> bytes: """Signs and timestamps a string so it cannot be forged. Normally used via set_secure_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored ...
[ "def", "create_signed_value", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "version", ":", "int", "=", "None", ")", "->", "bytes", ":", "self", ".", "require_setting", "(", "\"cookie_secret\"", "...
Signs and timestamps a string so it cannot be forged. Normally used via set_secure_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_secure_cookie. .. versionchanged:: 3.2.1 Added ...
[ "Signs", "and", "timestamps", "a", "string", "so", "it", "cannot", "be", "forged", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L719-L743
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_secure_cookie
def get_secure_cookie( self, name: str, value: str = None, max_age_days: int = 31, min_version: int = None, ) -> Optional[bytes]: """Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike ...
python
def get_secure_cookie( self, name: str, value: str = None, max_age_days: int = 31, min_version: int = None, ) -> Optional[bytes]: """Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike ...
[ "def", "get_secure_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "str", "=", "None", ",", "max_age_days", ":", "int", "=", "31", ",", "min_version", ":", "int", "=", "None", ",", ")", "->", "Optional", "[", "bytes", "]", ":", "s...
Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike `get_cookie`). Similar to `get_cookie`, this method only returns cookies that were present in the request. It does not see outgoing cookies set by `set_secure...
[ "Returns", "the", "given", "signed", "cookie", "if", "it", "validates", "or", "None", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L745-L775
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_secure_cookie_key_version
def get_secure_cookie_key_version( self, name: str, value: str = None ) -> Optional[int]: """Returns the signing key version of the secure cookie. The version is returned as int. """ self.require_setting("cookie_secret", "secure cookies") if value is None: ...
python
def get_secure_cookie_key_version( self, name: str, value: str = None ) -> Optional[int]: """Returns the signing key version of the secure cookie. The version is returned as int. """ self.require_setting("cookie_secret", "secure cookies") if value is None: ...
[ "def", "get_secure_cookie_key_version", "(", "self", ",", "name", ":", "str", ",", "value", ":", "str", "=", "None", ")", "->", "Optional", "[", "int", "]", ":", "self", ".", "require_setting", "(", "\"cookie_secret\"", ",", "\"secure cookies\"", ")", "if", ...
Returns the signing key version of the secure cookie. The version is returned as int.
[ "Returns", "the", "signing", "key", "version", "of", "the", "secure", "cookie", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L777-L789
train
tornadoweb/tornado
tornado/web.py
RequestHandler.redirect
def redirect(self, url: str, permanent: bool = False, status: int = None) -> None: """Sends a redirect to the given (optionally relative) URL. If the ``status`` argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chos...
python
def redirect(self, url: str, permanent: bool = False, status: int = None) -> None: """Sends a redirect to the given (optionally relative) URL. If the ``status`` argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chos...
[ "def", "redirect", "(", "self", ",", "url", ":", "str", ",", "permanent", ":", "bool", "=", "False", ",", "status", ":", "int", "=", "None", ")", "->", "None", ":", "if", "self", ".", "_headers_written", ":", "raise", "Exception", "(", "\"Cannot redire...
Sends a redirect to the given (optionally relative) URL. If the ``status`` argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the ``permanent`` argument. The default is 302 (temporary).
[ "Sends", "a", "redirect", "to", "the", "given", "(", "optionally", "relative", ")", "URL", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L791-L807
train
tornadoweb/tornado
tornado/web.py
RequestHandler.write
def write(self, chunk: Union[str, bytes, dict]) -> None: """Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``applicat...
python
def write(self, chunk: Union[str, bytes, dict]) -> None: """Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``applicat...
[ "def", "write", "(", "self", ",", "chunk", ":", "Union", "[", "str", ",", "bytes", ",", "dict", "]", ")", "->", "None", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"Cannot write() after finish()\"", ")", "if", "not", "isinst...
Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Conte...
[ "Writes", "the", "given", "chunk", "to", "the", "output", "buffer", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L809-L839
train
tornadoweb/tornado
tornado/web.py
RequestHandler.render
def render(self, template_name: str, **kwargs: Any) -> "Future[None]": """Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned b...
python
def render(self, template_name: str, **kwargs: Any) -> "Future[None]": """Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned b...
[ "def", "render", "(", "self", ",", "template_name", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "\"Future[None]\"", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"Cannot render() after finish()\"", ")", "html", "="...
Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned by `finish`. Awaiting this `.Future` is optional. .. versionchange...
[ "Renders", "the", "template", "with", "the", "given", "arguments", "as", "the", "response", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L841-L914
train
tornadoweb/tornado
tornado/web.py
RequestHandler.render_linked_js
def render_linked_js(self, js_files: Iterable[str]) -> str: """Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] ...
python
def render_linked_js(self, js_files: Iterable[str]) -> str: """Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] ...
[ "def", "render_linked_js", "(", "self", ",", "js_files", ":", "Iterable", "[", "str", "]", ")", "->", "str", ":", "paths", "=", "[", "]", "unique_paths", "=", "set", "(", ")", "# type: Set[str]", "for", "path", "in", "js_files", ":", "if", "not", "is_a...
Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output.
[ "Default", "method", "used", "to", "render", "the", "final", "js", "links", "for", "the", "rendered", "webpage", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L916-L937
train
tornadoweb/tornado
tornado/web.py
RequestHandler.render_embed_js
def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return ( b'<script type="text/javascript">\n//<!...
python
def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return ( b'<script type="text/javascript">\n//<!...
[ "def", "render_embed_js", "(", "self", ",", "js_embed", ":", "Iterable", "[", "bytes", "]", ")", "->", "bytes", ":", "return", "(", "b'<script type=\"text/javascript\">\\n//<![CDATA[\\n'", "+", "b\"\\n\"", ".", "join", "(", "js_embed", ")", "+", "b\"\\n//]]>\\n</s...
Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output.
[ "Default", "method", "used", "to", "render", "the", "final", "embedded", "js", "for", "the", "rendered", "webpage", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L939-L949
train
tornadoweb/tornado
tornado/web.py
RequestHandler.render_linked_css
def render_linked_css(self, css_files: Iterable[str]) -> str: """Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] ...
python
def render_linked_css(self, css_files: Iterable[str]) -> str: """Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] ...
[ "def", "render_linked_css", "(", "self", ",", "css_files", ":", "Iterable", "[", "str", "]", ")", "->", "str", ":", "paths", "=", "[", "]", "unique_paths", "=", "set", "(", ")", "# type: Set[str]", "for", "path", "in", "css_files", ":", "if", "not", "i...
Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output.
[ "Default", "method", "used", "to", "render", "the", "final", "css", "links", "for", "the", "rendered", "webpage", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L951-L971
train
tornadoweb/tornado
tornado/web.py
RequestHandler.render_embed_css
def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return b'<style type="text/css">\n' + b"\n".join(css_embe...
python
def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return b'<style type="text/css">\n' + b"\n".join(css_embe...
[ "def", "render_embed_css", "(", "self", ",", "css_embed", ":", "Iterable", "[", "bytes", "]", ")", "->", "bytes", ":", "return", "b'<style type=\"text/css\">\\n'", "+", "b\"\\n\"", ".", "join", "(", "css_embed", ")", "+", "b\"\\n</style>\"" ]
Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output.
[ "Default", "method", "used", "to", "render", "the", "final", "embedded", "css", "for", "the", "rendered", "webpage", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L973-L979
train
tornadoweb/tornado
tornado/web.py
RequestHandler.render_string
def render_string(self, template_name: str, **kwargs: Any) -> bytes: """Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above. """ # If no template_path is specified...
python
def render_string(self, template_name: str, **kwargs: Any) -> bytes: """Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above. """ # If no template_path is specified...
[ "def", "render_string", "(", "self", ",", "template_name", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "bytes", ":", "# If no template_path is specified, use the path of the calling file", "template_path", "=", "self", ".", "get_template_path", "(", ...
Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.
[ "Generate", "the", "given", "template", "with", "the", "given", "arguments", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L981-L1005
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_template_namespace
def get_template_namespace(self) -> Dict[str, Any]: """Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and k...
python
def get_template_namespace(self) -> Dict[str, Any]: """Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and k...
[ "def", "get_template_namespace", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "namespace", "=", "dict", "(", "handler", "=", "self", ",", "request", "=", "self", ".", "request", ",", "current_user", "=", "self", ".", "current_user", ...
Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and keyword arguments to `render` or `render_string`.
[ "Returns", "a", "dictionary", "to", "be", "used", "as", "the", "default", "template", "namespace", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1007-L1028
train
tornadoweb/tornado
tornado/web.py
RequestHandler.create_template_loader
def create_template_loader(self, template_path: str) -> template.BaseLoader: """Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` applica...
python
def create_template_loader(self, template_path: str) -> template.BaseLoader: """Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` applica...
[ "def", "create_template_loader", "(", "self", ",", "template_path", ":", "str", ")", "->", "template", ".", "BaseLoader", ":", "settings", "=", "self", ".", "application", ".", "settings", "if", "\"template_loader\"", "in", "settings", ":", "return", "settings",...
Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` application settings. If a ``template_loader`` application setting is supplied...
[ "Returns", "a", "new", "template", "loader", "for", "the", "given", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1030-L1049
train
tornadoweb/tornado
tornado/web.py
RequestHandler.flush
def flush(self, include_footers: bool = False) -> "Future[None]": """Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callbac...
python
def flush(self, include_footers: bool = False) -> "Future[None]": """Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callbac...
[ "def", "flush", "(", "self", ",", "include_footers", ":", "bool", "=", "False", ")", "->", "\"Future[None]\"", ":", "assert", "self", ".", "request", ".", "connection", "is", "not", "None", "chunk", "=", "b\"\"", ".", "join", "(", "self", ".", "_write_bu...
Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callback can be outstanding at a time; if another flush occurs before the pr...
[ "Flushes", "the", "current", "output", "buffer", "to", "the", "network", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1051-L1101
train
tornadoweb/tornado
tornado/web.py
RequestHandler.finish
def finish(self, chunk: Union[str, bytes, dict] = None) -> "Future[None]": """Finishes this response, ending the HTTP request. Passing a ``chunk`` to ``finish()`` is equivalent to passing that chunk to ``write()`` and then calling ``finish()`` with no arguments. Returns a `.Future` whi...
python
def finish(self, chunk: Union[str, bytes, dict] = None) -> "Future[None]": """Finishes this response, ending the HTTP request. Passing a ``chunk`` to ``finish()`` is equivalent to passing that chunk to ``write()`` and then calling ``finish()`` with no arguments. Returns a `.Future` whi...
[ "def", "finish", "(", "self", ",", "chunk", ":", "Union", "[", "str", ",", "bytes", ",", "dict", "]", "=", "None", ")", "->", "\"Future[None]\"", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"finish() called twice\"", ")", "i...
Finishes this response, ending the HTTP request. Passing a ``chunk`` to ``finish()`` is equivalent to passing that chunk to ``write()`` and then calling ``finish()`` with no arguments. Returns a `.Future` which may optionally be awaited to track the sending of the response to the clien...
[ "Finishes", "this", "response", "ending", "the", "HTTP", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1103-L1160
train
tornadoweb/tornado
tornado/web.py
RequestHandler.detach
def detach(self) -> iostream.IOStream: """Take control of the underlying stream. Returns the underlying `.IOStream` object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake. This method is only supporte...
python
def detach(self) -> iostream.IOStream: """Take control of the underlying stream. Returns the underlying `.IOStream` object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake. This method is only supporte...
[ "def", "detach", "(", "self", ")", "->", "iostream", ".", "IOStream", ":", "self", ".", "_finished", "=", "True", "# TODO: add detach to HTTPConnection?", "return", "self", ".", "request", ".", "connection", ".", "detach", "(", ")" ]
Take control of the underlying stream. Returns the underlying `.IOStream` object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake. This method is only supported when HTTP/1.1 is used. .. versionadded:...
[ "Take", "control", "of", "the", "underlying", "stream", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1162-L1175
train
tornadoweb/tornado
tornado/web.py
RequestHandler.send_error
def send_error(self, status_code: int = 500, **kwargs: Any) -> None: """Sends the given HTTP error code to the browser. If `flush()` has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet fl...
python
def send_error(self, status_code: int = 500, **kwargs: Any) -> None: """Sends the given HTTP error code to the browser. If `flush()` has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet fl...
[ "def", "send_error", "(", "self", ",", "status_code", ":", "int", "=", "500", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "_headers_written", ":", "gen_log", ".", "error", "(", "\"Cannot send error response after headers w...
Sends the given HTTP error code to the browser. If `flush()` has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page. O...
[ "Sends", "the", "given", "HTTP", "error", "code", "to", "the", "browser", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1182-L1218
train
tornadoweb/tornado
tornado/web.py
RequestHandler.write_error
def write_error(self, status_code: int, **kwargs: Any) -> None: """Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``e...
python
def write_error(self, status_code: int, **kwargs: Any) -> None: """Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``e...
[ "def", "write_error", "(", "self", ",", "status_code", ":", "int", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "settings", ".", "get", "(", "\"serve_traceback\"", ")", "and", "\"exc_info\"", "in", "kwargs", ":", "# i...
Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``exc_info`` triple will be available as ``kwargs["exc_info"]``. Note...
[ "Override", "to", "implement", "custom", "error", "pages", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1220-L1243
train
tornadoweb/tornado
tornado/web.py
RequestHandler.locale
def locale(self) -> tornado.locale.Locale: """The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` ...
python
def locale(self) -> tornado.locale.Locale: """The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` ...
[ "def", "locale", "(", "self", ")", "->", "tornado", ".", "locale", ".", "Locale", ":", "if", "not", "hasattr", "(", "self", ",", "\"_locale\"", ")", ":", "loc", "=", "self", ".", "get_user_locale", "(", ")", "if", "loc", "is", "not", "None", ":", "...
The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Add...
[ "The", "locale", "for", "the", "current", "session", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1246-L1264
train
tornadoweb/tornado
tornado/web.py
RequestHandler.get_browser_locale
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale: """Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 """ if "Accept-Language" in self.request.headers: languages = se...
python
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale: """Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 """ if "Accept-Language" in self.request.headers: languages = se...
[ "def", "get_browser_locale", "(", "self", ",", "default", ":", "str", "=", "\"en_US\"", ")", "->", "tornado", ".", "locale", ".", "Locale", ":", "if", "\"Accept-Language\"", "in", "self", ".", "request", ".", "headers", ":", "languages", "=", "self", ".", ...
Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
[ "Determines", "the", "user", "s", "locale", "from", "Accept", "-", "Language", "header", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1280-L1302
train
tornadoweb/tornado
tornado/web.py
RequestHandler.current_user
def current_user(self) -> Any: """The authenticated user for this request. This is set in one of two ways: * A subclass may override `get_current_user()`, which will be called automatically the first time ``self.current_user`` is accessed. `get_current_user()` will only be ...
python
def current_user(self) -> Any: """The authenticated user for this request. This is set in one of two ways: * A subclass may override `get_current_user()`, which will be called automatically the first time ``self.current_user`` is accessed. `get_current_user()` will only be ...
[ "def", "current_user", "(", "self", ")", "->", "Any", ":", "if", "not", "hasattr", "(", "self", ",", "\"_current_user\"", ")", ":", "self", ".", "_current_user", "=", "self", ".", "get_current_user", "(", ")", "return", "self", ".", "_current_user" ]
The authenticated user for this request. This is set in one of two ways: * A subclass may override `get_current_user()`, which will be called automatically the first time ``self.current_user`` is accessed. `get_current_user()` will only be called once per request, and is ...
[ "The", "authenticated", "user", "for", "this", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1305-L1338
train