language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
python-openxml__python-docx
tests/image/test_tiff.py
{ "start": 7912, "end": 9382 }
class ____: def it_can_iterate_through_the_directory_entries_in_an_IFD(self, iter_fixture): ( ifd_parser, _IfdEntryFactory_, stream_rdr, offsets, expected_entries, ) = iter_fixture entries = list(ifd_parser.iter_entries()) assert _IfdEntryFactory_.call_args_list == [ call(stream_rdr, offsets[0]), call(stream_rdr, offsets[1]), ] assert entries == expected_entries # fixtures ------------------------------------------------------- @pytest.fixture def ifd_entry_(self, request): return instance_mock(request, _IfdEntry, tag=1, value=42) @pytest.fixture def ifd_entry_2_(self, request): return instance_mock(request, _IfdEntry, tag=2, value=24) @pytest.fixture def _IfdEntryFactory_(self, request, ifd_entry_, ifd_entry_2_): return function_mock( request, "docx.image.tiff._IfdEntryFactory", side_effect=[ifd_entry_, ifd_entry_2_], ) @pytest.fixture def iter_fixture(self, _IfdEntryFactory_, ifd_entry_, ifd_entry_2_): stream_rdr = StreamReader(io.BytesIO(b"\x00\x02"), BIG_ENDIAN) offsets = [2, 14] ifd_parser = _IfdParser(stream_rdr, offset=0) expected_entries = [ifd_entry_, ifd_entry_2_] return (ifd_parser, _IfdEntryFactory_, stream_rdr, offsets, expected_entries)
Describe_IfdParser
python
anthropics__anthropic-sdk-python
src/anthropic/types/raw_content_block_start_event.py
{ "start": 795, "end": 929 }
class ____(BaseModel): content_block: ContentBlock index: int type: Literal["content_block_start"]
RawContentBlockStartEvent
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/refurb/FURB189.py
{ "start": 654, "end": 891 }
class ____(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Activity state. This is an optional property and if not provided, the state will be Active by default. """ ACTIVE = "Active" INACTIVE = "Inactive"
ActivityState
python
getsentry__sentry
tests/sentry/api/endpoints/test_auth_validate.py
{ "start": 242, "end": 1956 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.user = self.create_user() self.user.set_password("ThisIsATestPassword1234") self.user.save() self.org = self.create_organization(owner=self.user) self.url = reverse("sentry-api-0-auth-test") def test_valid_session_auth(self) -> None: self.client.login(username=self.user.username, password="ThisIsATestPassword1234") response = self.client.get(self.url, format="json") assert response.status_code == 200 self.client.logout() def test_valid_user_token_auth(self) -> None: api_token = ApiToken.objects.create(token_type=AuthTokenType.USER, user=self.user) self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_token.plaintext_token}") response = self.client.get(self.url) assert response.status_code == 200 self.client.credentials() def test_valid_org_token_auth(self) -> None: from sentry.utils.security.orgauthtoken_token import hash_token token = "sntrys_abc1234_xyz" _ = self.create_org_auth_token( name="test_valid_org_token_auth", token_hashed=hash_token(token), organization_id=self.org.id, token_last_characters="xyz", scope_list=[], date_last_used=None, ) self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}") response = self.client.get(self.url) assert response.status_code == 200 self.client.credentials() def test_no_auth(self) -> None: response = self.client.get(self.url) assert response.status_code == 403
AuthenticatedTest
python
huggingface__transformers
src/transformers/models/yolos/image_processing_yolos.py
{ "start": 2091, "end": 26869 }
class ____(ImagesKwargs, total=False): r""" format (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`): Data format of the annotations. One of "coco_detection" or "coco_panoptic". do_convert_annotations (`bool`, *optional*, defaults to `True`): Controls whether to convert the annotations to the format expected by the YOLOS model. Converts the bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`. Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method. return_segmentation_masks (`bool`, *optional*, defaults to `False`): Whether to return segmentation masks. annotations (`AnnotationType` or `list[AnnotationType]`, *optional*): Annotations to transform according to the padding that is applied to the images. masks_path (`str` or `pathlib.Path`, *optional*): Path to the directory containing the segmentation masks. """ format: Union[str, AnnotationFormat] do_convert_annotations: bool return_segmentation_masks: bool annotations: Optional[Union[AnnotationType, list[AnnotationType]]] masks_path: Optional[Union[str, pathlib.Path]] # Copied from transformers.models.detr.image_processing_detr.get_max_height_width def get_max_height_width( images: list[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None ) -> list[int]: """ Get the maximum height and width across all images in a batch. """ if input_data_format is None: input_data_format = infer_channel_dimension_format(images[0]) if input_data_format == ChannelDimension.FIRST: _, max_height, max_width = max_across_indices([img.shape for img in images]) elif input_data_format == ChannelDimension.LAST: max_height, max_width, _ = max_across_indices([img.shape for img in images]) else: raise ValueError(f"Invalid channel dimension format: {input_data_format}") return (max_height, max_width) def get_size_with_aspect_ratio( image_size: tuple[int, int], size: int, max_size: Optional[int] = None, mod_size: int = 16 ) -> tuple[int, int]: """ Computes the output image size given the input image size and the desired output size with multiple of divisible_size. Args: image_size (`tuple[int, int]`): The input image size. size (`int`): The desired output size. max_size (`int`, *optional*): The maximum allowed output size. mod_size (`int`, *optional*): The size to make multiple of mod_size. """ height, width = image_size raw_size = None if max_size is not None: min_original_size = float(min((height, width))) max_original_size = float(max((height, width))) if max_original_size / min_original_size * size > max_size: raw_size = max_size * min_original_size / max_original_size size = int(round(raw_size)) if width < height: ow = size if max_size is not None and raw_size is not None: oh = int(raw_size * height / width) else: oh = int(size * height / width) elif (height <= width and height == size) or (width <= height and width == size): oh, ow = height, width else: oh = size if max_size is not None and raw_size is not None: ow = int(raw_size * width / height) else: ow = int(size * width / height) if mod_size is not None: ow_mod = np.mod(ow, mod_size) oh_mod = np.mod(oh, mod_size) ow = ow - ow_mod oh = oh - oh_mod return (oh, ow) # Copied from transformers.models.detr.image_processing_detr.get_image_size_for_max_height_width def get_image_size_for_max_height_width( input_image: np.ndarray, max_height: int, max_width: int, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> tuple[int, int]: """ Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio. Important, even if image_height < max_height and image_width < max_width, the image will be resized to at least one of the edges be equal to max_height or max_width. For example: - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50) - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400) Args: input_image (`np.ndarray`): The image to resize. max_height (`int`): The maximum allowed height. max_width (`int`): The maximum allowed width. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format of the input image. If not provided, it will be inferred from the input image. """ image_size = get_image_size(input_image, input_data_format) height, width = image_size height_scale = max_height / height width_scale = max_width / width min_scale = min(height_scale, width_scale) new_height = int(height * min_scale) new_width = int(width * min_scale) return new_height, new_width # Copied from transformers.models.detr.image_processing_detr.get_resize_output_image_size def get_resize_output_image_size( input_image: np.ndarray, size: Union[int, tuple[int, int], list[int]], max_size: Optional[int] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> tuple[int, int]: """ Computes the output image size given the input image size and the desired output size. If the desired output size is a tuple or list, the output image size is returned as is. If the desired output size is an integer, the output image size is computed by keeping the aspect ratio of the input image size. Args: input_image (`np.ndarray`): The image to resize. size (`int` or `tuple[int, int]` or `list[int]`): The desired output size. max_size (`int`, *optional*): The maximum allowed output size. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format of the input image. If not provided, it will be inferred from the input image. """ image_size = get_image_size(input_image, input_data_format) if isinstance(size, (list, tuple)): return size return get_size_with_aspect_ratio(image_size, size, max_size) # Copied from transformers.models.detr.image_processing_detr.safe_squeeze def safe_squeeze(arr: np.ndarray, axis: Optional[int] = None) -> np.ndarray: """ Squeezes an array, but only if the axis specified has dim 1. """ if axis is None: return arr.squeeze() try: return arr.squeeze(axis=axis) except ValueError: return arr # Copied from transformers.models.detr.image_processing_detr.normalize_annotation def normalize_annotation(annotation: dict, image_size: tuple[int, int]) -> dict: image_height, image_width = image_size norm_annotation = {} for key, value in annotation.items(): if key == "boxes": boxes = value boxes = corners_to_center_format(boxes) boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32) norm_annotation[key] = boxes else: norm_annotation[key] = value return norm_annotation # Copied from transformers.models.detr.image_processing_detr.max_across_indices def max_across_indices(values: Iterable[Any]) -> list[Any]: """ Return the maximum value across all indices of an iterable of values. """ return [max(values_i) for values_i in zip(*values)] # Copied from transformers.models.detr.image_processing_detr.make_pixel_mask def make_pixel_mask( image: np.ndarray, output_size: tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None ) -> np.ndarray: """ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding. Args: image (`np.ndarray`): Image to make the pixel mask for. output_size (`tuple[int, int]`): Output size of the mask. """ input_height, input_width = get_image_size(image, channel_dim=input_data_format) mask = np.zeros(output_size, dtype=np.int64) mask[:input_height, :input_width] = 1 return mask # Copied from transformers.models.detr.image_processing_detr.convert_coco_poly_to_mask def convert_coco_poly_to_mask(segmentations, height: int, width: int) -> np.ndarray: """ Convert a COCO polygon annotation to a mask. Args: segmentations (`list[list[float]]`): List of polygons, each polygon represented by a list of x-y coordinates. height (`int`): Height of the mask. width (`int`): Width of the mask. """ try: from pycocotools import mask as coco_mask except ImportError: raise ImportError("Pycocotools is not installed in your environment.") masks = [] for polygons in segmentations: rles = coco_mask.frPyObjects(polygons, height, width) mask = coco_mask.decode(rles) if len(mask.shape) < 3: mask = mask[..., None] mask = np.asarray(mask, dtype=np.uint8) mask = np.any(mask, axis=2) masks.append(mask) if masks: masks = np.stack(masks, axis=0) else: masks = np.zeros((0, height, width), dtype=np.uint8) return masks # Copied from transformers.models.detr.image_processing_detr.prepare_coco_detection_annotation def prepare_coco_detection_annotation( image, target, return_segmentation_masks: bool = False, input_data_format: Optional[Union[ChannelDimension, str]] = None, ): """ Convert the target in COCO format into the format expected by DETR. """ image_height, image_width = get_image_size(image, channel_dim=input_data_format) image_id = target["image_id"] image_id = np.asarray([image_id], dtype=np.int64) # Get all COCO annotations for the given image. annotations = target["annotations"] annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0] classes = [obj["category_id"] for obj in annotations] classes = np.asarray(classes, dtype=np.int64) # for conversion to coco api area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32) iscrowd = np.asarray([obj.get("iscrowd", 0) for obj in annotations], dtype=np.int64) boxes = [obj["bbox"] for obj in annotations] # guard against no boxes via resizing boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4) boxes[:, 2:] += boxes[:, :2] boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width) boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height) keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0]) new_target = {} new_target["image_id"] = image_id new_target["class_labels"] = classes[keep] new_target["boxes"] = boxes[keep] new_target["area"] = area[keep] new_target["iscrowd"] = iscrowd[keep] new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64) if annotations and "keypoints" in annotations[0]: keypoints = [obj["keypoints"] for obj in annotations] # Converting the filtered keypoints list to a numpy array keypoints = np.asarray(keypoints, dtype=np.float32) # Apply the keep mask here to filter the relevant annotations keypoints = keypoints[keep] num_keypoints = keypoints.shape[0] keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints new_target["keypoints"] = keypoints if return_segmentation_masks: segmentation_masks = [obj["segmentation"] for obj in annotations] masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width) new_target["masks"] = masks[keep] return new_target # Copied from transformers.models.detr.image_processing_detr.masks_to_boxes def masks_to_boxes(masks: np.ndarray) -> np.ndarray: """ Compute the bounding boxes around the provided panoptic segmentation masks. Args: masks: masks in format `[number_masks, height, width]` where N is the number of masks Returns: boxes: bounding boxes in format `[number_masks, 4]` in xyxy format """ if masks.size == 0: return np.zeros((0, 4)) h, w = masks.shape[-2:] y = np.arange(0, h, dtype=np.float32) x = np.arange(0, w, dtype=np.float32) # see https://github.com/pytorch/pytorch/issues/50276 y, x = np.meshgrid(y, x, indexing="ij") x_mask = masks * np.expand_dims(x, axis=0) x_max = x_mask.reshape(x_mask.shape[0], -1).max(-1) x = np.ma.array(x_mask, mask=~(np.array(masks, dtype=bool))) x_min = x.filled(fill_value=1e8) x_min = x_min.reshape(x_min.shape[0], -1).min(-1) y_mask = masks * np.expand_dims(y, axis=0) y_max = y_mask.reshape(x_mask.shape[0], -1).max(-1) y = np.ma.array(y_mask, mask=~(np.array(masks, dtype=bool))) y_min = y.filled(fill_value=1e8) y_min = y_min.reshape(y_min.shape[0], -1).min(-1) return np.stack([x_min, y_min, x_max, y_max], 1) # Copied from transformers.models.detr.image_processing_detr.prepare_coco_panoptic_annotation with DETR->YOLOS def prepare_coco_panoptic_annotation( image: np.ndarray, target: dict, masks_path: Union[str, pathlib.Path], return_masks: bool = True, input_data_format: Union[ChannelDimension, str] = None, ) -> dict: """ Prepare a coco panoptic annotation for YOLOS. """ image_height, image_width = get_image_size(image, channel_dim=input_data_format) annotation_path = pathlib.Path(masks_path) / target["file_name"] new_target = {} new_target["image_id"] = np.asarray([target["image_id"] if "image_id" in target else target["id"]], dtype=np.int64) new_target["size"] = np.asarray([image_height, image_width], dtype=np.int64) new_target["orig_size"] = np.asarray([image_height, image_width], dtype=np.int64) if "segments_info" in target: masks = np.asarray(PIL.Image.open(annotation_path), dtype=np.uint32) masks = rgb_to_id(masks) ids = np.array([segment_info["id"] for segment_info in target["segments_info"]]) masks = masks == ids[:, None, None] masks = masks.astype(np.uint8) if return_masks: new_target["masks"] = masks new_target["boxes"] = masks_to_boxes(masks) new_target["class_labels"] = np.array( [segment_info["category_id"] for segment_info in target["segments_info"]], dtype=np.int64 ) new_target["iscrowd"] = np.asarray( [segment_info["iscrowd"] for segment_info in target["segments_info"]], dtype=np.int64 ) new_target["area"] = np.asarray( [segment_info["area"] for segment_info in target["segments_info"]], dtype=np.float32 ) return new_target # Copied from transformers.models.detr.image_processing_detr.get_segmentation_image def get_segmentation_image( masks: np.ndarray, input_size: tuple, target_size: tuple, stuff_equiv_classes, deduplicate=False ): h, w = input_size final_h, final_w = target_size m_id = scipy.special.softmax(masks.transpose(0, 1), -1) if m_id.shape[-1] == 0: # We didn't detect any mask :( m_id = np.zeros((h, w), dtype=np.int64) else: m_id = m_id.argmax(-1).reshape(h, w) if deduplicate: # Merge the masks corresponding to the same stuff class for equiv in stuff_equiv_classes.values(): for eq_id in equiv: m_id[m_id == eq_id] = equiv[0] seg_img = id_to_rgb(m_id) seg_img = resize(seg_img, (final_w, final_h), resample=PILImageResampling.NEAREST) return seg_img # Copied from transformers.models.detr.image_processing_detr.get_mask_area def get_mask_area(seg_img: np.ndarray, target_size: tuple[int, int], n_classes: int) -> np.ndarray: final_h, final_w = target_size np_seg_img = seg_img.astype(np.uint8) np_seg_img = np_seg_img.reshape(final_h, final_w, 3) m_id = rgb_to_id(np_seg_img) area = [(m_id == i).sum() for i in range(n_classes)] return area # Copied from transformers.models.detr.image_processing_detr.score_labels_from_class_probabilities def score_labels_from_class_probabilities(logits: np.ndarray) -> tuple[np.ndarray, np.ndarray]: probs = scipy.special.softmax(logits, axis=-1) labels = probs.argmax(-1, keepdims=True) scores = np.take_along_axis(probs, labels, axis=-1) scores, labels = scores.squeeze(-1), labels.squeeze(-1) return scores, labels # Copied from transformers.models.detr.image_processing_detr.resize_annotation def resize_annotation( annotation: dict[str, Any], orig_size: tuple[int, int], target_size: tuple[int, int], threshold: float = 0.5, resample: PILImageResampling = PILImageResampling.NEAREST, ): """ Resizes an annotation to a target size. Args: annotation (`dict[str, Any]`): The annotation dictionary. orig_size (`tuple[int, int]`): The original size of the input image. target_size (`tuple[int, int]`): The target size of the image, as returned by the preprocessing `resize` step. threshold (`float`, *optional*, defaults to 0.5): The threshold used to binarize the segmentation masks. resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`): The resampling filter to use when resizing the masks. """ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size)) ratio_height, ratio_width = ratios new_annotation = {} new_annotation["size"] = target_size for key, value in annotation.items(): if key == "boxes": boxes = value scaled_boxes = boxes * np.asarray([ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32) new_annotation["boxes"] = scaled_boxes elif key == "area": area = value scaled_area = area * (ratio_width * ratio_height) new_annotation["area"] = scaled_area elif key == "masks": masks = value[:, None] masks = np.array([resize(mask, target_size, resample=resample) for mask in masks]) masks = masks.astype(np.float32) masks = masks[:, 0] > threshold new_annotation["masks"] = masks elif key == "size": new_annotation["size"] = target_size else: new_annotation[key] = value return new_annotation # Copied from transformers.models.detr.image_processing_detr.binary_mask_to_rle def binary_mask_to_rle(mask): """ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format. Args: mask (`torch.Tensor` or `numpy.array`): A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target segment_id or class_id. Returns: `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE format. """ if is_torch_tensor(mask): mask = mask.numpy() pixels = mask.flatten() pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return list(runs) # Copied from transformers.models.detr.image_processing_detr.convert_segmentation_to_rle def convert_segmentation_to_rle(segmentation): """ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format. Args: segmentation (`torch.Tensor` or `numpy.array`): A segmentation map of shape `(height, width)` where each value denotes a segment or class id. Returns: `list[List]`: A list of lists, where each list is the run-length encoding of a segment / class id. """ segment_ids = torch.unique(segmentation) run_length_encodings = [] for idx in segment_ids: mask = torch.where(segmentation == idx, 1, 0) rle = binary_mask_to_rle(mask) run_length_encodings.append(rle) return run_length_encodings # Copied from transformers.models.detr.image_processing_detr.remove_low_and_no_objects def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels): """ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`. Args: masks (`torch.Tensor`): A tensor of shape `(num_queries, height, width)`. scores (`torch.Tensor`): A tensor of shape `(num_queries)`. labels (`torch.Tensor`): A tensor of shape `(num_queries)`. object_mask_threshold (`float`): A number between 0 and 1 used to binarize the masks. Raises: `ValueError`: Raised when the first dimension doesn't match in all input tensors. Returns: `tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region < `object_mask_threshold`. """ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]): raise ValueError("mask, scores and labels must have the same shape!") to_keep = labels.ne(num_labels) & (scores > object_mask_threshold) return masks[to_keep], scores[to_keep], labels[to_keep] # Copied from transformers.models.detr.image_processing_detr.check_segment_validity def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8): # Get the mask associated with the k class mask_k = mask_labels == k mask_k_area = mask_k.sum() # Compute the area of all the stuff in query k original_area = (mask_probs[k] >= mask_threshold).sum() mask_exists = mask_k_area > 0 and original_area > 0 # Eliminate disconnected tiny segments if mask_exists: area_ratio = mask_k_area / original_area if not area_ratio.item() > overlap_mask_area_threshold: mask_exists = False return mask_exists, mask_k # Copied from transformers.models.detr.image_processing_detr.compute_segments def compute_segments( mask_probs, pred_scores, pred_labels, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, label_ids_to_fuse: Optional[set[int]] = None, target_size: Optional[tuple[int, int]] = None, ): height = mask_probs.shape[1] if target_size is None else target_size[0] width = mask_probs.shape[2] if target_size is None else target_size[1] segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device) segments: list[dict] = [] if target_size is not None: mask_probs = nn.functional.interpolate( mask_probs.unsqueeze(0), size=target_size, mode="bilinear", align_corners=False )[0] current_segment_id = 0 # Weigh each mask by its prediction score mask_probs *= pred_scores.view(-1, 1, 1) mask_labels = mask_probs.argmax(0) # [height, width] # Keep track of instances of each class stuff_memory_list: dict[str, int] = {} for k in range(pred_labels.shape[0]): pred_class = pred_labels[k].item() should_fuse = pred_class in label_ids_to_fuse # Check if mask exists and large enough to be a segment mask_exists, mask_k = check_segment_validity( mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold ) if mask_exists: if pred_class in stuff_memory_list: current_segment_id = stuff_memory_list[pred_class] else: current_segment_id += 1 # Add current object segment to final segmentation map segmentation[mask_k] = current_segment_id segment_score = round(pred_scores[k].item(), 6) segments.append( { "id": current_segment_id, "label_id": pred_class, "was_fused": should_fuse, "score": segment_score, } ) if should_fuse: stuff_memory_list[pred_class] = current_segment_id return segmentation, segments @requires(backends=("vision",))
YolosImageProcessorKwargs
python
Textualize__textual
src/textual/events.py
{ "start": 23282, "end": 23921 }
class ____(Event, bubble=True): """Event containing text that was pasted into the Textual application. This event will only appear when running in a terminal emulator that supports bracketed paste mode. Textual will enable bracketed pastes when an app starts, and disable it when the app shuts down. - [X] Bubbles - [ ] Verbose Args: text: The text that has been pasted. """ def __init__(self, text: str) -> None: super().__init__() self.text = text """The text that was pasted.""" def __rich_repr__(self) -> rich.repr.Result: yield "text", self.text
Paste
python
pypa__warehouse
tests/unit/email/test_init.py
{ "start": 109288, "end": 111606 }
class ____: @pytest.fixture def _team(self, pyramid_user): self.user = pyramid_user self.organization_name = "exampleorganization" self.team_name = "Example Team" @pytest.mark.usefixtures("_team") @pytest.mark.parametrize( ("email_template_name", "send_team_email"), [ ("team-created", email.send_team_created_email), ("team-deleted", email.send_team_deleted_email), ], ) def test_send_team_email( self, db_request, make_email_renderers, send_email, email_template_name, send_team_email, ): subject_renderer, body_renderer, html_renderer = make_email_renderers( email_template_name ) result = send_team_email( db_request, self.user, organization_name=self.organization_name, team_name=self.team_name, ) assert result == { "organization_name": self.organization_name, "team_name": self.team_name, } subject_renderer.assert_(**result) body_renderer.assert_(**result) html_renderer.assert_(**result) assert db_request.task.calls == [pretend.call(send_email)] assert send_email.delay.calls == [ pretend.call( f"{self.user.name} <{self.user.email}>", { "sender": None, "subject": subject_renderer.string_response, "body_text": body_renderer.string_response, "body_html": ( f"<html>\n" f"<head></head>\n" f"<body><p>{html_renderer.string_response}</p></body>\n" f"</html>\n" ), }, { "tag": "account:email:sent", "user_id": self.user.id, "additional": { "from_": db_request.registry.settings["mail.sender"], "to": self.user.email, "subject": subject_renderer.string_response, "redact_ip": False, }, }, ) ]
TestTeamEmails
python
pypa__hatch
tests/utils/test_fs.py
{ "start": 88, "end": 3463 }
class ____: def test_type(self): expected_type = type(pathlib.Path()) assert isinstance(Path(), expected_type) assert issubclass(Path, expected_type) def test_resolve_relative_non_existent(self, tmp_path): origin = os.getcwd() os.chdir(tmp_path) try: expected_representation = os.path.join(tmp_path, "foo") assert str(Path("foo").resolve()) == expected_representation assert str(Path(".", "foo").resolve()) == expected_representation finally: os.chdir(origin) def test_ensure_dir_exists(self, tmp_path): path = Path(tmp_path, "foo") path.ensure_dir_exists() assert path.is_dir() def test_ensure_parent_dir_exists(self, tmp_path): path = Path(tmp_path, "foo", "bar") path.ensure_parent_dir_exists() assert path.parent.is_dir() assert not path.is_dir() def test_as_cwd(self, tmp_path): origin = os.getcwd() with Path(tmp_path).as_cwd(): assert os.getcwd() == str(tmp_path) assert os.getcwd() == origin def test_as_cwd_env_vars(self, tmp_path): env_var = str(self).encode().hex().upper() origin = os.getcwd() with Path(tmp_path).as_cwd(env_vars={env_var: "foo"}): assert os.getcwd() == str(tmp_path) assert os.environ.get(env_var) == "foo" assert os.getcwd() == origin assert env_var not in os.environ def test_remove_file(self, tmp_path): path = Path(tmp_path, "foo") path.touch() assert path.is_file() path.remove() assert not path.exists() def test_remove_directory(self, tmp_path): path = Path(tmp_path, "foo") path.mkdir() assert path.is_dir() path.remove() assert not path.exists() def test_remove_non_existent(self, tmp_path): path = Path(tmp_path, "foo") assert not path.exists() path.remove() assert not path.exists() def test_temp_hide_file(self, tmp_path): path = Path(tmp_path, "foo") path.touch() with path.temp_hide() as temp_path: assert not path.exists() assert temp_path.is_file() assert path.is_file() assert not temp_path.exists() def test_temp_hide_dir(self, tmp_path): path = Path(tmp_path, "foo") path.mkdir() with path.temp_hide() as temp_path: assert not path.exists() assert temp_path.is_dir() assert path.is_dir() assert not temp_path.exists() def test_temp_hide_non_existent(self, tmp_path): path = Path(tmp_path, "foo") with path.temp_hide() as temp_path: assert not path.exists() assert not temp_path.exists() assert not path.exists() assert not temp_path.exists() def test_temp_directory(): with temp_directory() as temp_dir: assert isinstance(temp_dir, Path) assert temp_dir.is_dir() assert not temp_dir.exists() def test_temp_chdir(): origin = os.getcwd() with temp_chdir() as temp_dir: assert isinstance(temp_dir, Path) assert temp_dir.is_dir() assert os.getcwd() == str(temp_dir) assert os.getcwd() == origin assert not temp_dir.exists()
TestPath
python
milvus-io__pymilvus
tests/test_bulk_writer_validators.py
{ "start": 274, "end": 2484 }
class ____: def test_valid_list(self): """Test valid list of floats""" result = float_vector_validator([1.0, 2.0, 3.0], 3) assert result == [1.0, 2.0, 3.0] def test_invalid_list_length(self): """Test list with wrong dimension""" with pytest.raises(MilvusException, match="array's length must be equal to vector dimension"): float_vector_validator([1.0, 2.0], 3) def test_invalid_list_type(self): """Test list with non-float elements""" with pytest.raises(MilvusException, match="array's element must be float value"): float_vector_validator([1.0, 2, 3.0], 3) def test_valid_numpy_float32(self): """Test valid numpy array with float32""" arr = np.array([1.0, 2.0, 3.0], dtype=np.float32) result = float_vector_validator(arr, 3) assert result == [1.0, 2.0, 3.0] def test_valid_numpy_float64(self): """Test valid numpy array with float64""" arr = np.array([1.0, 2.0, 3.0], dtype=np.float64) result = float_vector_validator(arr, 3) assert result == [1.0, 2.0, 3.0] def test_invalid_numpy_dtype(self): """Test numpy array with invalid dtype""" arr = np.array([1, 2, 3], dtype=np.int32) with pytest.raises(MilvusException, match='dtype must be "float32" or "float64"'): float_vector_validator(arr, 3) def test_invalid_numpy_shape(self): """Test numpy array with wrong shape""" arr = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) with pytest.raises(MilvusException, match="shape must not be one dimension"): float_vector_validator(arr, 4) def test_invalid_numpy_length(self): """Test numpy array with wrong dimension""" arr = np.array([1.0, 2.0], dtype=np.float32) with pytest.raises(MilvusException, match="length must be equal to vector dimension"): float_vector_validator(arr, 3) def test_invalid_type(self): """Test with invalid input type""" with pytest.raises(MilvusException, match="only accept numpy.ndarray or list"): float_vector_validator("invalid", 3)
TestFloatVectorValidator
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/formatted_text/html.py
{ "start": 3835, "end": 4374 }
class ____(Formatter): def format_field(self, value: object, format_spec: str) -> str: return html_escape(format(value, format_spec)) def html_escape(text: object) -> str: # The string interpolation functions also take integers and other types. # Convert to string first. if not isinstance(text, str): text = f"{text}" return ( text.replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace('"', "&quot;") ) FORMATTER = HTMLFormatter()
HTMLFormatter
python
sympy__sympy
sympy/polys/numberfields/modules.py
{ "start": 27753, "end": 42205 }
class ____(Module, IntegerPowerable): """A submodule of another module.""" def __init__(self, parent, matrix, denom=1, mult_tab=None): """ Parameters ========== parent : :py:class:`~.Module` The module from which this one is derived. matrix : :py:class:`~.DomainMatrix` over :ref:`ZZ` The matrix whose columns define this submodule's generators as linear combinations over the parent's generators. denom : int, optional (default=1) Denominator for the coefficients given by the matrix. mult_tab : dict, ``None``, optional If already known, the multiplication table for this module may be supplied. """ self._parent = parent self._matrix = matrix self._denom = denom self._mult_tab = mult_tab self._n = matrix.shape[1] self._QQ_matrix = None self._starts_with_unity = None self._is_sq_maxrank_HNF = None def __repr__(self): r = 'Submodule' + repr(self.matrix.transpose().to_Matrix().tolist()) if self.denom > 1: r += f'/{self.denom}' return r def reduced(self): """ Produce a reduced version of this submodule. Explanation =========== In the reduced version, it is guaranteed that 1 is the only positive integer dividing both the submodule's denominator, and every entry in the submodule's matrix. Returns ======= :py:class:`~.Submodule` """ if self.denom == 1: return self g = igcd(self.denom, *self.coeffs) if g == 1: return self return type(self)(self.parent, (self.matrix / g).convert_to(ZZ), denom=self.denom // g, mult_tab=self._mult_tab) def discard_before(self, r): """ Produce a new module by discarding all generators before a given index *r*. """ W = self.matrix[:, r:] s = self.n - r M = None mt = self._mult_tab if mt is not None: M = {} for u in range(s): M[u] = {} for v in range(u, s): M[u][v] = mt[r + u][r + v][r:] return Submodule(self.parent, W, denom=self.denom, mult_tab=M) @property def n(self): return self._n def mult_tab(self): if self._mult_tab is None: self.compute_mult_tab() return self._mult_tab def compute_mult_tab(self): gens = self.basis_element_pullbacks() M = {} n = self.n for u in range(n): M[u] = {} for v in range(u, n): M[u][v] = self.represent(gens[u] * gens[v]).flat() self._mult_tab = M @property def parent(self): return self._parent @property def matrix(self): return self._matrix @property def coeffs(self): return self.matrix.flat() @property def denom(self): return self._denom @property def QQ_matrix(self): """ :py:class:`~.DomainMatrix` over :ref:`QQ`, equal to ``self.matrix / self.denom``, and guaranteed to be dense. Explanation =========== Depending on how it is formed, a :py:class:`~.DomainMatrix` may have an internal representation that is sparse or dense. We guarantee a dense representation here, so that tests for equivalence of submodules always come out as expected. Examples ======== >>> from sympy.polys import Poly, cyclotomic_poly, ZZ >>> from sympy.abc import x >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.numberfields.modules import PowerBasis >>> T = Poly(cyclotomic_poly(5, x)) >>> A = PowerBasis(T) >>> B = A.submodule_from_matrix(3*DomainMatrix.eye(4, ZZ), denom=6) >>> C = A.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=2) >>> print(B.QQ_matrix == C.QQ_matrix) True Returns ======= :py:class:`~.DomainMatrix` over :ref:`QQ` """ if self._QQ_matrix is None: self._QQ_matrix = (self.matrix / self.denom).to_dense() return self._QQ_matrix def starts_with_unity(self): if self._starts_with_unity is None: self._starts_with_unity = self(0).equiv(1) return self._starts_with_unity def is_sq_maxrank_HNF(self): if self._is_sq_maxrank_HNF is None: self._is_sq_maxrank_HNF = is_sq_maxrank_HNF(self._matrix) return self._is_sq_maxrank_HNF def is_power_basis_submodule(self): return isinstance(self.parent, PowerBasis) def element_from_rational(self, a): if self.starts_with_unity(): return self(0) * a else: return self.parent.element_from_rational(a) def basis_element_pullbacks(self): """ Return list of this submodule's basis elements as elements of the submodule's parent module. """ return [e.to_parent() for e in self.basis_elements()] def represent(self, elt): """ Represent a module element as an integer-linear combination over the generators of this module. See Also ======== .Module.represent .PowerBasis.represent """ if elt.module == self: return elt.column() elif elt.module == self.parent: try: # The given element should be a ZZ-linear combination over our # basis vectors; however, due to the presence of denominators, # we need to solve over QQ. A = self.QQ_matrix b = elt.QQ_col x = A._solve(b)[0].transpose() x = x.convert_to(ZZ) except DMBadInputError: raise ClosureFailure('Element outside QQ-span of this basis.') except CoercionFailed: raise ClosureFailure('Element in QQ-span but not ZZ-span of this basis.') return x elif isinstance(self.parent, Submodule): coeffs_in_parent = self.parent.represent(elt) parent_element = self.parent(coeffs_in_parent) return self.represent(parent_element) else: raise ClosureFailure('Element outside ancestor chain of this module.') def is_compat_submodule(self, other): return isinstance(other, Submodule) and other.parent == self.parent def __eq__(self, other): if self.is_compat_submodule(other): return other.QQ_matrix == self.QQ_matrix return NotImplemented def add(self, other, hnf=True, hnf_modulus=None): """ Add this :py:class:`~.Submodule` to another. Explanation =========== This represents the module generated by the union of the two modules' sets of generators. Parameters ========== other : :py:class:`~.Submodule` hnf : boolean, optional (default=True) If ``True``, reduce the matrix of the combined module to its Hermite Normal Form. hnf_modulus : :ref:`ZZ`, None, optional If a positive integer is provided, use this as modulus in the HNF reduction. See :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`. Returns ======= :py:class:`~.Submodule` """ d, e = self.denom, other.denom m = ilcm(d, e) a, b = m // d, m // e B = (a * self.matrix).hstack(b * other.matrix) if hnf: B = hermite_normal_form(B, D=hnf_modulus) return self.parent.submodule_from_matrix(B, denom=m) def __add__(self, other): if self.is_compat_submodule(other): return self.add(other) return NotImplemented __radd__ = __add__ def mul(self, other, hnf=True, hnf_modulus=None): """ Multiply this :py:class:`~.Submodule` by a rational number, a :py:class:`~.ModuleElement`, or another :py:class:`~.Submodule`. Explanation =========== To multiply by a rational number or :py:class:`~.ModuleElement` means to form the submodule whose generators are the products of this quantity with all the generators of the present submodule. To multiply by another :py:class:`~.Submodule` means to form the submodule whose generators are all the products of one generator from the one submodule, and one generator from the other. Parameters ========== other : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.ModuleElement`, :py:class:`~.Submodule` hnf : boolean, optional (default=True) If ``True``, reduce the matrix of the product module to its Hermite Normal Form. hnf_modulus : :ref:`ZZ`, None, optional If a positive integer is provided, use this as modulus in the HNF reduction. See :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`. Returns ======= :py:class:`~.Submodule` """ if is_rat(other): a, b = get_num_denom(other) if a == b == 1: return self else: return Submodule(self.parent, self.matrix * a, denom=self.denom * b, mult_tab=None).reduced() elif isinstance(other, ModuleElement) and other.module == self.parent: # The submodule is multiplied by an element of the parent module. # We presume this means we want a new submodule of the parent module. gens = [other * e for e in self.basis_element_pullbacks()] return self.parent.submodule_from_gens(gens, hnf=hnf, hnf_modulus=hnf_modulus) elif self.is_compat_submodule(other): # This case usually means you're multiplying ideals, and want another # ideal, i.e. another submodule of the same parent module. alphas, betas = self.basis_element_pullbacks(), other.basis_element_pullbacks() gens = [a * b for a in alphas for b in betas] return self.parent.submodule_from_gens(gens, hnf=hnf, hnf_modulus=hnf_modulus) return NotImplemented def __mul__(self, other): return self.mul(other) __rmul__ = __mul__ def _first_power(self): return self def reduce_element(self, elt): r""" If this submodule $B$ has defining matrix $W$ in square, maximal-rank Hermite normal form, then, given an element $x$ of the parent module $A$, we produce an element $y \in A$ such that $x - y \in B$, and the $i$th coordinate of $y$ satisfies $0 \leq y_i < w_{i,i}$. This representative $y$ is unique, in the sense that every element of the coset $x + B$ reduces to it under this procedure. Explanation =========== In the special case where $A$ is a power basis for a number field $K$, and $B$ is a submodule representing an ideal $I$, this operation represents one of a few important ways of reducing an element of $K$ modulo $I$ to obtain a "small" representative. See [Cohen00]_ Section 1.4.3. Examples ======== >>> from sympy import QQ, Poly, symbols >>> t = symbols('t') >>> k = QQ.alg_field_from_poly(Poly(t**3 + t**2 - 2*t + 8)) >>> Zk = k.maximal_order() >>> A = Zk.parent >>> B = (A(2) - 3*A(0))*Zk >>> B.reduce_element(A(2)) [3, 0, 0] Parameters ========== elt : :py:class:`~.ModuleElement` An element of this submodule's parent module. Returns ======= elt : :py:class:`~.ModuleElement` An element of this submodule's parent module. Raises ====== NotImplementedError If the given :py:class:`~.ModuleElement` does not belong to this submodule's parent module. StructureError If this submodule's defining matrix is not in square, maximal-rank Hermite normal form. References ========== .. [Cohen00] Cohen, H. *Advanced Topics in Computational Number Theory.* """ if not elt.module == self.parent: raise NotImplementedError if not self.is_sq_maxrank_HNF(): msg = "Reduction not implemented unless matrix square max-rank HNF" raise StructureError(msg) B = self.basis_element_pullbacks() a = elt for i in range(self.n - 1, -1, -1): b = B[i] q = a.coeffs[i]*b.denom // (b.coeffs[i]*a.denom) a -= q*b return a def is_sq_maxrank_HNF(dm): r""" Say whether a :py:class:`~.DomainMatrix` is in that special case of Hermite Normal Form, in which the matrix is also square and of maximal rank. Explanation =========== We commonly work with :py:class:`~.Submodule` instances whose matrix is in this form, and it can be useful to be able to check that this condition is satisfied. For example this is the case with the :py:class:`~.Submodule` ``ZK`` returned by :py:func:`~sympy.polys.numberfields.basis.round_two`, which represents the maximal order in a number field, and with ideals formed therefrom, such as ``2 * ZK``. """ if dm.domain.is_ZZ and dm.is_square and dm.is_upper: n = dm.shape[0] for i in range(n): d = dm[i, i].element if d <= 0: return False for j in range(i + 1, n): if not (0 <= dm[i, j].element < d): return False return True return False def make_mod_elt(module, col, denom=1): r""" Factory function which builds a :py:class:`~.ModuleElement`, but ensures that it is a :py:class:`~.PowerBasisElement` if the module is a :py:class:`~.PowerBasis`. """ if isinstance(module, PowerBasis): return PowerBasisElement(module, col, denom=denom) else: return ModuleElement(module, col, denom=denom)
Submodule
python
bokeh__bokeh
src/bokeh/models/text.py
{ "start": 2177, "end": 2456 }
class ____(MathText): """ Render mathematical content using `AsciiMath <http://asciimath.org/>`_ notation. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs)
Ascii
python
huggingface__transformers
tests/models/convbert/test_modeling_convbert.py
{ "start": 1413, "end": 9762 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): return ConvBertConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=False, initializer_range=self.initializer_range, ) def prepare_config_and_inputs_for_decoder(self): ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = self.prepare_config_and_inputs() config.is_decoder = True encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def create_and_check_model( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = ConvBertModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) result = model(input_ids, token_type_ids=token_type_ids) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_for_masked_lm( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = ConvBertForMaskedLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_for_question_answering( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = ConvBertForQuestionAnswering(config=config) model.to(torch_device) model.eval() result = model( input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, start_positions=sequence_labels, end_positions=sequence_labels, ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def create_and_check_for_sequence_classification( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = ConvBertForSequenceClassification(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def create_and_check_for_token_classification( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = ConvBertForTokenClassification(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def create_and_check_for_multiple_choice( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_choices = self.num_choices model = ConvBertForMultipleChoice(config=config) model.to(torch_device) model.eval() multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() result = model( multiple_choice_inputs_ids, attention_mask=multiple_choice_input_mask, token_type_ids=multiple_choice_token_type_ids, labels=choice_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch
ConvBertModelTester
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 2303, "end": 2392 }
class ____(TypedDict): name: str permissions: List[WeaviatePermission]
WeaviateRole
python
numba__llvmlite
llvmlite/ir/transforms.py
{ "start": 978, "end": 1552 }
class ____(CallVisitor): def __init__(self, orig, repl): super(ReplaceCalls, self).__init__() self.orig = orig self.repl = repl self.calls = [] def visit_Call(self, instr): if instr.callee == self.orig: instr.replace_callee(self.repl) self.calls.append(instr) def replace_all_calls(mod, orig, repl): """Replace all calls to `orig` to `repl` in module `mod`. Returns the references to the returned calls """ rc = ReplaceCalls(orig, repl) rc.visit(mod) return rc.calls
ReplaceCalls
python
google__jax
jax/_src/pallas/fuser/custom_fusion_lib.py
{ "start": 1776, "end": 1967 }
class ____(Protocol): def __call__( self, ctx: CustomEvalContext, *args: Any, ) -> Sequence[Any]: ... @custom_api_util.register_custom_decorator_type
CustomEvalRuleFn
python
realpython__materials
inheritance-and-composition/composition/employees.py
{ "start": 1074, "end": 1578 }
class ____: def __init__(self, id, name, address, role, payroll): self.id = id self.name = name self.address = address self.role = role self.payroll = payroll def work(self, hours): duties = self.role.perform_duties(hours) print(f"Employee {self.id} - {self.name}:") print(f"- {duties}") print("") self.payroll.track_work(hours) def calculate_payroll(self): return self.payroll.calculate_payroll()
Employee
python
getsentry__sentry
src/sentry/logging/handlers.py
{ "start": 5048, "end": 5638 }
class ____(logging.Handler): def emit(self, record, logger=None): """ Turn something like: > django.request.Forbidden (CSRF cookie not set.): /account into: > django.request.forbidden_csrf_cookie_not_set and track it as an incremented counter. """ key = record.name + "." + record.getMessage() key = key.lower() key = whitespace_re.sub("_", key) key = metrics_badchars_re.sub("", key) key = ".".join(key.split(".")[:3]) metrics.incr(key, skip_internal=False)
MetricsLogHandler
python
ray-project__ray
python/ray/serve/tests/test_fastapi.py
{ "start": 13860, "end": 31229 }
class ____(BaseModel): a: str # https://github.com/ray-project/ray/issues/16757 b: List[str] def test_fastapi_nested_field_in_response_model(serve_instance): app = FastAPI() @app.get("/", response_model=TestModel) def test_endpoint(): test_model = TestModel(a="a", b=["b"]) return test_model @serve.deployment @serve.ingress(app) class TestDeployment: # https://github.com/ray-project/ray/issues/17363 @app.get("/inner", response_model=TestModel) def test_endpoint_2(self): test_model = TestModel(a="a", b=["b"]) return test_model # https://github.com/ray-project/ray/issues/24710 @app.get("/inner2", response_model=List[TestModel]) def test_endpoint_3(self): test_model = TestModel(a="a", b=["b"]) return [test_model] serve.run(TestDeployment.bind()) url = get_application_url("HTTP") resp = httpx.get(url) assert resp.json() == {"a": "a", "b": ["b"]} resp = httpx.get(f"{url}/inner") assert resp.json() == {"a": "a", "b": ["b"]} resp = httpx.get(f"{url}/inner2") assert resp.json() == [{"a": "a", "b": ["b"]}] def test_fastapiwrapper_constructor_before_startup_hooks(serve_instance): """ Tests that the class constructor is called before the startup hooks are run in FastAPIWrapper. SignalActor event is set from a startup hook and is awaited in the class constructor. If the class constructor is run before the startup hooks, the SignalActor event will time out while waiting and the test will pass. """ app = FastAPI() signal = SignalActor.remote() @app.on_event("startup") def startup_event(): ray.get(signal.send.remote()) @serve.deployment @serve.ingress(app) class TestDeployment: def __init__(self): self.test_passed = False try: ray.get(signal.wait.remote(), timeout=0.1) self.test_passed = False except GetTimeoutError: self.test_passed = True @app.get("/") def root(self): return self.test_passed serve.run(TestDeployment.bind()) url = get_application_url("HTTP") resp = httpx.get(url) assert resp.json() def test_fastapi_shutdown_hook(serve_instance): # https://github.com/ray-project/ray/issues/18349 shutdown_signal = SignalActor.remote() del_signal = SignalActor.remote() app = FastAPI() @app.on_event("shutdown") def call_signal(): shutdown_signal.send.remote() @serve.deployment @serve.ingress(app) class A: def __del__(self): del_signal.send.remote() serve.run(A.bind()) serve.delete(SERVE_DEFAULT_APP_NAME) ray.get(shutdown_signal.wait.remote(), timeout=20) ray.get(del_signal.wait.remote(), timeout=20) def test_fastapi_shutdown_hook_async(serve_instance): # https://github.com/ray-project/ray/issues/41261 shutdown_signal = SignalActor.remote() del_signal = SignalActor.remote() app = FastAPI() @app.on_event("shutdown") def call_signal(): shutdown_signal.send.remote() @serve.deployment @serve.ingress(app) class A: async def __del__(self): del_signal.send.remote() serve.run(A.bind()) serve.delete(SERVE_DEFAULT_APP_NAME) ray.get(shutdown_signal.wait.remote(), timeout=20) ray.get(del_signal.wait.remote(), timeout=20) def test_fastapi_method_redefinition(serve_instance): app = FastAPI() @serve.deployment @serve.ingress(app) class A: @app.get("/") def method(self): return "hi get" @app.post("/") # noqa: F811 method redefinition def method(self): # noqa: F811 method redefinition return "hi post" serve.run(A.bind(), route_prefix="/a") url = get_application_url("HTTP") assert httpx.get(f"{url}/").json() == "hi get" assert httpx.post(f"{url}/").json() == "hi post" def test_fastapi_same_app_multiple_deployments(serve_instance): # https://github.com/ray-project/ray/issues/21264 app = FastAPI() @serve.deployment @serve.ingress(app) class CounterDeployment1: @app.get("/incr") def incr(self): return "incr" @app.get("/decr") def decr(self): return "decr" @serve.deployment @serve.ingress(app) class CounterDeployment2: @app.get("/incr2") def incr2(self): return "incr2" @app.get("/decr2") def decr2(self): return "decr2" serve.run(CounterDeployment1.bind(), name="app1", route_prefix="/app1") serve.run(CounterDeployment2.bind(), name="app2", route_prefix="/app2") app1_url = get_application_url("HTTP", app_name="app1") app2_url = get_application_url("HTTP", app_name="app2") should_work = [ (app1_url, "/incr", "incr"), (app1_url, "/decr", "decr"), (app2_url, "/incr2", "incr2"), (app2_url, "/decr2", "decr2"), ] for url, path, resp in should_work: assert httpx.get(f"{url}{path}").json() == resp, (path, resp) should_404 = [ (app1_url, "/incr2", 404), (app1_url, "/decr2", 404), (app2_url, "/incr", 404), (app2_url, "/decr", 404), ] for url, path, status_code in should_404: assert httpx.get(f"{url}{path}").status_code == status_code, (path, status_code) @pytest.mark.parametrize("two_fastapi", [True, False]) @pytest.mark.parametrize("docs_url", ["/docs", None]) def test_two_fastapi_in_one_application( serve_instance: ServeControllerClient, two_fastapi, docs_url ): """ Check that a deployment graph that would normally work, will not deploy successfully if there are two FastAPI deployments. """ app1 = FastAPI(docs_url=docs_url) app2 = FastAPI(docs_url=docs_url) class SubModel: def add(self, a: int): return a + 1 @serve.deployment @serve.ingress(app1) class Model: def __init__(self, submodel: DeploymentHandle): self.submodel = submodel @app1.get("/{a}") async def func(self, a: int): return await self.submodel.add.remote(a) if two_fastapi: SubModel = serve.deployment(serve.ingress(app2)(SubModel)) with pytest.raises(RayServeException) as e: handle = serve.run(Model.bind(SubModel.bind()), name="app1") assert "FastAPI" in str(e.value) else: handle = serve.run(Model.bind(serve.deployment(SubModel).bind()), name="app1") assert handle.func.remote(5).result() == 6 @pytest.mark.parametrize( "is_fastapi,docs_path", [ (False, None), # Not integrated with FastAPI (True, "/docs"), # Don't specify docs_url, use default (True, "/documentation"), # Override default docs url ], ) def test_fastapi_docs_path( serve_instance: ServeControllerClient, is_fastapi, docs_path ): # If not the default docs_url, override it. if docs_path != "/docs": app = FastAPI(docs_url=docs_path) else: app = FastAPI() class Model: @app.get("/{a}") def func(a: int): return {"result": a} if is_fastapi: Model = serve.ingress(app)(Model) serve.run(serve.deployment(Model).bind(), name="app1") wait_for_condition( lambda: ray.get(serve_instance._controller.get_docs_path.remote("app1")) == docs_path ) def fastapi_builder(): app = FastAPI(docs_url="/custom-docs") @app.get("/") def f1(): return "hello" router = APIRouter() @router.get("/f2") def f2(): return "hello f2" @router.get("/error") def error(): raise ValueError("some error") app.include_router(router) # add a middleware @app.middleware("http") async def add_process_time_header(request: Request, call_next): response = await call_next(request) response.headers["X-Custom-Middleware"] = "fake-middleware" return response # custom exception handler @app.exception_handler(ValueError) async def custom_exception_handler(request: Request, exc: ValueError): return JSONResponse(status_code=500, content={"error": "fake-error"}) return app def test_ingress_with_fastapi_routes_outside_deployment(serve_instance): app = fastapi_builder() @serve.deployment @serve.ingress(app) class ASGIIngress: @app.get("/class_route") def class_route(self): return "hello class route" serve.run(ASGIIngress.bind()) url = get_application_url("HTTP") assert httpx.get(url).json() == "hello" assert httpx.get(f"{url}/f2").json() == "hello f2" assert httpx.get(f"{url}/class_route").json() == "hello class route" assert httpx.get(f"{url}/error").status_code == 500 assert httpx.get(f"{url}/error").json() == {"error": "fake-error"} # get the docs path from the controller docs_path = ray.get(serve_instance._controller.get_docs_path.remote("default")) assert docs_path == "/custom-docs" def test_ingress_with_fastapi_with_no_deployment_class(serve_instance): app = fastapi_builder() ingress_deployment = serve.deployment(serve.ingress(app)()) assert ingress_deployment.name == "ASGIIngressDeployment" serve.run(ingress_deployment.bind()) url = get_application_url("HTTP") assert httpx.get(url).json() == "hello" assert httpx.get(f"{url}/f2").json() == "hello f2" assert httpx.get(f"{url}/error").status_code == 500 assert httpx.get(f"{url}/error").json() == {"error": "fake-error"} # get the docs path from the controller docs_path = ray.get(serve_instance._controller.get_docs_path.remote("default")) assert docs_path == "/custom-docs" def test_ingress_with_fastapi_builder_function(serve_instance): ingress_deployment = serve.deployment(serve.ingress(fastapi_builder)()) serve.run(ingress_deployment.bind()) url = get_application_url("HTTP") resp = httpx.get(url) assert resp.json() == "hello" assert resp.headers["X-Custom-Middleware"] == "fake-middleware" resp = httpx.get(f"{url}/f2") assert resp.json() == "hello f2" assert resp.headers["X-Custom-Middleware"] == "fake-middleware" resp = httpx.get(f"{url}/error") assert resp.status_code == 500 assert resp.json() == {"error": "fake-error"} docs_path = ray.get(serve_instance._controller.get_docs_path.remote("default")) assert docs_path == "/custom-docs" def test_ingress_with_fastapi_builder_with_deployment_class(serve_instance): @serve.deployment @serve.ingress(fastapi_builder) class ASGIIngress: def __init__(self): pass serve.run(ASGIIngress.bind()) url = get_application_url("HTTP") resp = httpx.get(url) assert resp.json() == "hello" resp = httpx.get(f"{url}/f2") assert resp.json() == "hello f2" resp = httpx.get(f"{url}/error") assert resp.status_code == 500 assert resp.json() == {"error": "fake-error"} # get the docs path from the controller docs_path = ray.get(serve_instance._controller.get_docs_path.remote("default")) assert docs_path == "/custom-docs" def test_ingress_with_fastapi_with_native_deployment(serve_instance): app = fastapi_builder() class ASGIIngress: def __call__(self): pass with pytest.raises(ValueError) as e: serve.ingress(app)(ASGIIngress) assert "Classes passed to @serve.ingress may not have __call__ method." in str( e.value ) def sub_deployment(): @serve.deployment class SubModel: def __call__(self, a: int): return a + 1 return SubModel.options(name="sub_deployment") def fastapi_builder_with_sub_deployment(): app = fastapi_builder() def get_sub_deployment_handle(): return serve.get_deployment_handle(sub_deployment().name, "default") class Data(BaseModel): a: int @app.get("/sub_deployment", response_model=Data) async def f( request: Request, handle: DeploymentHandle = Depends(get_sub_deployment_handle) ): a = int(request.query_params.get("a", 1)) result = await handle.remote(a) return Data(a=result) return app def test_deployment_composition_with_builder_function(serve_instance): @serve.deployment @serve.ingress(fastapi_builder_with_sub_deployment) class ASGIIngress: def __init__(self, sub_deployment: DeploymentHandle): self.sub_deployment = sub_deployment serve.run(ASGIIngress.bind(sub_deployment().bind())) url = get_application_url("HTTP") resp = httpx.get(f"{url}/sub_deployment?a=2") assert resp.json() == {"a": 3} def test_deployment_composition_with_builder_function_without_decorator(serve_instance): app = serve.deployment(serve.ingress(fastapi_builder_with_sub_deployment)()) # the default ingress deployment returned from serve.ingress accepts args and kwargs # and passes them to the deployment constructor serve.run(app.bind(sub_deployment().bind())) url = get_application_url("HTTP") resp = httpx.get(f"{url}/sub_deployment?a=2") assert resp.json() == {"a": 3} def starlette_builder(): from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import JSONResponse from starlette.routing import Route, Router # Define route handlers async def homepage(request): return JSONResponse("hello") async def f2(request): return JSONResponse("hello f2") async def error(request): raise ValueError("some error") # Create a router for additional routes router = Router( [ Route("/f2", f2), Route("/error", error), ] ) # Create a middleware for adding headers class CustomHeaderMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): response = await call_next(request) response.headers["X-Custom-Middleware"] = "fake-middleware" return response # Custom exception handler for ValueError def handle_value_error(request, exc): return JSONResponse(status_code=500, content={"error": "fake-error"}) exception_handlers = {ValueError: handle_value_error} # Configure routes for the main app routes = [ Route("/", homepage), ] # Create the Starlette app with middleware and exception handlers app = Starlette( routes=routes, middleware=[Middleware(CustomHeaderMiddleware)], exception_handlers=exception_handlers, ) # Mount the router to the main app app.mount("/", router) return app def test_ingress_with_starlette_app_with_no_deployment_class(serve_instance): ingress_deployment = serve.deployment(serve.ingress(starlette_builder())()) serve.run(ingress_deployment.bind()) url = get_application_url("HTTP") resp = httpx.get(url) assert resp.json() == "hello" assert resp.headers["X-Custom-Middleware"] == "fake-middleware" resp = httpx.get(f"{url}/f2") assert resp.json() == "hello f2" assert resp.headers["X-Custom-Middleware"] == "fake-middleware" resp = httpx.get(f"{url}/error") assert resp.status_code == 500 assert resp.json() == {"error": "fake-error"} docs_path = ray.get(serve_instance._controller.get_docs_path.remote("default")) assert docs_path is None def test_ingress_with_starlette_builder_with_no_deployment_class(serve_instance): ingress_deployment = serve.deployment(serve.ingress(starlette_builder)()) serve.run(ingress_deployment.bind()) url = get_application_url("HTTP") resp = httpx.get(url) assert resp.json() == "hello" assert resp.headers["X-Custom-Middleware"] == "fake-middleware" resp = httpx.get(f"{url}/f2") assert resp.json() == "hello f2" assert resp.headers["X-Custom-Middleware"] == "fake-middleware" resp = httpx.get(f"{url}/error") assert resp.status_code == 500 assert resp.json() == {"error": "fake-error"} docs_path = ray.get(serve_instance._controller.get_docs_path.remote("default")) assert docs_path is None def test_ingress_with_starlette_builder_with_deployment_class(serve_instance): @serve.deployment @serve.ingress(starlette_builder) class ASGIIngress: def __init__(self): pass serve.run(ASGIIngress.bind()) url = get_application_url("HTTP") resp = httpx.get(url) assert resp.json() == "hello" assert resp.headers["X-Custom-Middleware"] == "fake-middleware" resp = httpx.get(f"{url}/f2") assert resp.json() == "hello f2" assert resp.headers["X-Custom-Middleware"] == "fake-middleware" resp = httpx.get(f"{url}/error") assert resp.status_code == 500 assert resp.json() == {"error": "fake-error"} docs_path = ray.get(serve_instance._controller.get_docs_path.remote("default")) assert docs_path is None if __name__ == "__main__": import sys sys.exit(pytest.main(["-v", "-s", __file__]))
TestModel
python
pypa__warehouse
warehouse/integrations/secrets/utils.py
{ "start": 392, "end": 2115 }
class ____: def __init__( self, name, key_id_header, signature_header, verification_url, api_token=None ): # The display name of the integrator self.name = name # The headers that we expect to be present for each integrator self.key_id_header = key_id_header self.signature_header = signature_header # The URL that we use to get the public key to verify the signature self.verification_url = verification_url # The key for the setting which contains an API token, if necessary, to include # with the request to the above URL self.api_token = api_token @property def metric_name(self): """Normalized version of the display name""" return self.name.lower().replace(".", "") @property def headers(self): """Set of all headers that must be present""" return {self.key_id_header, self.signature_header} def to_dict(self): return { "name": self.name, "key_id_header": self.key_id_header, "signature_header": self.signature_header, "verification_url": self.verification_url, "api_token": self.api_token, } @classmethod def from_dict(cls, data): return cls(**data) def __eq__(self, other): if not isinstance(other, DisclosureOrigin): return False return ( self.name == other.name and self.key_id_header == other.key_id_header and self.signature_header == other.signature_header and self.verification_url == other.verification_url and self.api_token == other.api_token )
DisclosureOrigin
python
django-compressor__django-compressor
compressor/tests/test_parsers.py
{ "start": 5026, "end": 5133 }
class ____(ParserTestCase, CompressorTestCase): parser_cls = "compressor.parser.HtmlParser"
HtmlParserTests
python
pytorch__pytorch
torch/distributed/_tools/mem_tracker.py
{ "start": 3301, "end": 4639 }
class ____: """ A class to store the memory statistics of a module. Args: mod_fqn (str): The fully qualified name of the module. Attributes: mod_fqn (str): The fully qualified name of the module. parameter_mem (int): The memory usage of the parameters of the module. buffer_mem (int): The memory usage of the buffers of the module. input_mem (int): The memory usage of the inputs to the module. output_mem (int): The memory usage of the outputs from the module. snapshots (Dict[_ModState, Dict[torch.device, Dict[str, int]]]): A dictionary of memory snapshots of the module at different states defined by ``_ModState``. Note: The memory snapshot is stored as a dictionary - Dict[torch.device, Dict[str, int]], where each key is a device, and each value is another dictionary with keys as memory reference types defined by `_MemRefType` and values as the memory consumed in bytes. """ def __init__(self, mod_fqn: str): self.mod_fqn = mod_fqn self.parameter_mem: int self.buffer_mem: int self.input_mem: int self.output_mem: int self.local_peak: dict[torch.device, int] = {} self.snapshots: dict[_ModState, list[dict[torch.device, dict[str, int]]]] = {}
_ModMemStats
python
scipy__scipy
scipy/stats/tests/test_hypotests.py
{ "start": 83624, "end": 88480 }
class ____: # data with unequal variances data_same_size = ([24., 23., 31., 51.], [34., 18., 18., 26.], [17., 68., 59., 7.]) data_diff_size = ([30., 23., 51.], [-81., 71., -27., 63.], [42., 11., 29., 19., 50.], [23., 22., 20., 18., 9.]) spss_same_size = """ Mean Diff Lower Bound Upper Bound Sig 0 - 1 8.25000000 -16.5492749527311 33.0492749527311 0.558733632413559 0 - 2 -5.50000000 -63.6702454316458 52.6702454316458 0.941147750599221 1 - 2 -13.7500000 -74.3174374251372 46.8174374251372 0.682983914946841 """ spss_diff_size = """ Mean Diff Lower Bound Upper Bound Sig 0 - 1 28.16666667 -141.985416377670 198.318749711003 0.8727542747886180 0 - 2 4.466666667 -37.2830676783904 46.2164010117237 0.9752628408671710 0 - 3 16.26666667 -35.0933112382470 67.6266445715803 0.4262506151302880 1 - 2 -23.70000000 -195.315617201249 147.915617201249 0.9148950609000590 1 - 3 -11.90000000 -188.105478728519 164.305478728519 0.9861432250093960 2 - 3 11.80000000 -16.2894857524254 39.8894857524254 0.4755344436335670 """ @pytest.mark.xslow @pytest.mark.parametrize("data, res_expect_str", ((data_same_size, spss_same_size), (data_diff_size, spss_diff_size)), ids=["equal size sample", "unequal sample size"]) def test_compare_spss(self, data, res_expect_str): """ DATA LIST LIST /Group (F1.0) Value (F8.2). BEGIN DATA 0 24 0 23 0 31 0 51 1 34 1 18 1 18 1 26 2 17 2 68 2 59 2 7 END DATA. ONEWAY Value BY Group /MISSING ANALYSIS /POSTHOC=GH ALPHA(0.05). """ res_expect = np.asarray( res_expect_str.replace(" - ", " ").split()[7:], dtype=float).reshape(-1, 6) res_games = stats.tukey_hsd(*data, equal_var=False) conf = res_games.confidence_interval() # loop over the comparisons for i, j, s, l, h, p in res_expect: i, j = int(i), int(j) assert_allclose(res_games.statistic[i, j], s, atol=1e-8) assert_allclose(res_games.pvalue[i, j], p, atol=1e-8) assert_allclose(conf.low[i, j], l, atol=1e-6) assert_allclose(conf.high[i, j], h, atol=1e-5) r_same_size = """ q value Pr(>|q|) 1 - 0 == 0 -1.5467805948856344 0.55873362851759 2 - 0 == 0 0.4726721776628535 0.94114775035993 2 - 1 == 0 1.246837541297872 0.68298393799782 """ r_diff_size = """ q value Pr(>|q|) 1 - 0 == 0 -1.0589317485313876 0.87275427357438 2 - 0 == 0 -0.5716222106144833 0.97526284087419 3 - 0 == 0 -2.6209678382077000 0.42625067714691 2 - 1 == 0 0.8971899898179028 0.91489506061850 3 - 1 == 0 0.4579447210555352 0.98614322544695 3 - 2 == 0 -2.198800177874794 0.47553444364614 """ @pytest.mark.parametrize("data, res_expect_str", ((data_same_size, r_same_size), (data_diff_size, r_diff_size)), ids=["equal size sample", "unequal sample size"]) def test_compare_r(self, data, res_expect_str): """ games-howell is provided by PMCMRplus package https://search.r-project.org/CRAN/refmans/PMCMRplus/html/gamesHowellTest.html > library("PMCMRplus") > options(digits=16) > table = data.frame( values = c(24., 23., 31., 51., 34., 18., 18., 26., 17., 68., 59., 7.), groups = c("0", "0", "0", "0", "1", "1", "1", "1", "2", "2", "2", "2") ) > table$groups = as.factor(table$groups) > fit <-aov(values ~ groups, table) > res = gamesHowellTest(fit) > summary(res) """ res_expect = np.asarray( res_expect_str.replace(" - ", " ") .replace(" == ", " ").split()[3:], dtype=float).reshape(-1, 5) res_games = stats.tukey_hsd(*data, equal_var=False) # loop over the comparisons # note confidence intervals are not provided by PMCMRplus for j, i, _, _, p in res_expect: i, j = int(i), int(j) assert_allclose(res_games.pvalue[i, j], p, atol=1e-7) # Data validation test has been covered by TestTukeyHSD # like empty, 1d, inf, and lack of tretments # because games_howell leverage _tukey_hsd_iv()
TestGamesHowell
python
aio-libs__aiohttp
aiohttp/http_parser.py
{ "start": 2140, "end": 2451 }
class ____(NamedTuple): version: HttpVersion code: int reason: str headers: CIMultiDictProxy[str] raw_headers: RawHeaders should_close: bool compression: str | None upgrade: bool chunked: bool _MsgT = TypeVar("_MsgT", RawRequestMessage, RawResponseMessage)
RawResponseMessage
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-pgvector/destination_pgvector/destination.py
{ "start": 705, "end": 3320 }
class ____(Destination): sql_processor: pgvector_processor.PGVectorProcessor def _init_sql_processor( self, config: ConfigModel, configured_catalog: Optional[ConfiguredAirbyteCatalog] = None ) -> None: self.sql_processor = pgvector_processor.PGVectorProcessor( sql_config=pgvector_processor.PostgresConfig( host=config.indexing.host, port=config.indexing.port, database=config.indexing.database, schema_name=config.indexing.default_schema, username=config.indexing.username, password=SecretString(config.indexing.credentials.password), ), splitter_config=config.processing, embedder_config=config.embedding, # type: ignore [arg-type] # No common base class catalog_provider=CatalogProvider(configured_catalog), temp_dir=Path(tempfile.mkdtemp()), temp_file_cleanup=True, ) def write( self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage], ) -> Iterable[AirbyteMessage]: parsed_config = ConfigModel.parse_obj(config) self._init_sql_processor(config=parsed_config, configured_catalog=configured_catalog) yield from self.sql_processor.process_airbyte_messages_as_generator( messages=input_messages, write_strategy=WriteStrategy.AUTO, ) def check(self, logger: Logger, config: Mapping[str, Any]) -> AirbyteConnectionStatus: _ = logger # Unused try: parsed_config = ConfigModel.parse_obj(config) self._init_sql_processor(config=parsed_config) self.sql_processor.sql_config.connect() return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e: return AirbyteConnectionStatus( status=Status.FAILED, message=f"An exception occurred: {repr(e)}" ) def spec(self, *args: Any, **kwargs: Any) -> ConnectorSpecification: return ConnectorSpecification( documentationUrl="https://docs.airbyte.com/integrations/destinations/pgvector", supportsIncremental=True, supported_destination_sync_modes=[ DestinationSyncMode.overwrite, DestinationSyncMode.append, DestinationSyncMode.append_dedup, ], connectionSpecification=ConfigModel.schema(), # type: ignore[attr-defined] )
DestinationPGVector
python
pandas-dev__pandas
pandas/tests/frame/indexing/test_coercion.py
{ "start": 376, "end": 5125 }
class ____: @pytest.mark.parametrize("consolidate", [True, False]) def test_loc_setitem_multiindex_columns(self, consolidate): # GH#18415 Setting values in a single column preserves dtype, # while setting them in multiple columns did unwanted cast. # Note that A here has 2 blocks, below we do the same thing # with a consolidated frame. A = DataFrame(np.zeros((6, 5), dtype=np.float32)) A = pd.concat([A, A], axis=1, keys=[1, 2]) if consolidate: A = A._consolidate() A.loc[2:3, (1, slice(2, 3))] = np.ones((2, 2), dtype=np.float32) assert (A.dtypes == np.float32).all() A.loc[0:5, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32) assert (A.dtypes == np.float32).all() A.loc[:, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32) assert (A.dtypes == np.float32).all() # TODO: i think this isn't about MultiIndex and could be done with iloc? def test_37477(): # fixed by GH#45121 orig = DataFrame({"A": [1, 2, 3], "B": [3, 4, 5]}) df = orig.copy() with pytest.raises(TypeError, match="Invalid value"): df.at[1, "B"] = 1.2 with pytest.raises(TypeError, match="Invalid value"): df.loc[1, "B"] = 1.2 with pytest.raises(TypeError, match="Invalid value"): df.iat[1, 1] = 1.2 with pytest.raises(TypeError, match="Invalid value"): df.iloc[1, 1] = 1.2 def test_6942(indexer_al): # check that the .at __setitem__ after setting "Live" actually sets the data start = Timestamp("2014-04-01") t1 = Timestamp("2014-04-23 12:42:38.883082") t2 = Timestamp("2014-04-24 01:33:30.040039") dti = date_range(start, periods=1) orig = DataFrame(index=dti, columns=["timenow", "Live"]) df = orig.copy() indexer_al(df)[start, "timenow"] = t1 df["Live"] = True df.at[start, "timenow"] = t2 assert df.iloc[0, 0] == t2 def test_26395(indexer_al): # .at case fixed by GH#45121 (best guess) df = DataFrame(index=["A", "B", "C"]) df["D"] = 0 indexer_al(df)["C", "D"] = 2 expected = DataFrame({"D": [0, 0, 2]}, index=["A", "B", "C"], dtype=np.int64) tm.assert_frame_equal(df, expected) with pytest.raises(TypeError, match="Invalid value"): indexer_al(df)["C", "D"] = 44.5 with pytest.raises(TypeError, match="Invalid value"): indexer_al(df)["C", "D"] = "hello" @pytest.mark.xfail(reason="unwanted upcast") def test_15231(): df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"]) df.loc[2] = Series({"a": 5, "b": 6}) assert (df.dtypes == np.int64).all() df.loc[3] = Series({"a": 7}) # df["a"] doesn't have any NaNs, should not have been cast exp_dtypes = Series([np.int64, np.float64], dtype=object, index=["a", "b"]) tm.assert_series_equal(df.dtypes, exp_dtypes) def test_iloc_setitem_unnecesssary_float_upcasting(): # GH#12255 df = DataFrame( { 0: np.array([1, 3], dtype=np.float32), 1: np.array([2, 4], dtype=np.float32), 2: ["a", "b"], } ) orig = df.copy() values = df[0].values.reshape(2, 1) df.iloc[:, 0:1] = values tm.assert_frame_equal(df, orig) @pytest.mark.xfail(reason="unwanted casting to dt64") def test_12499(): # TODO: OP in GH#12499 used np.datetim64("NaT") instead of pd.NaT, # which has consequences for the expected df["two"] (though i think at # the time it might not have because of a separate bug). See if it makes # a difference which one we use here. ts = Timestamp("2016-03-01 03:13:22.98986", tz="UTC") data = [{"one": 0, "two": ts}] orig = DataFrame(data) df = orig.copy() df.loc[1] = [np.nan, NaT] expected = DataFrame( {"one": [0, np.nan], "two": Series([ts, NaT], dtype="datetime64[ns, UTC]")} ) tm.assert_frame_equal(df, expected) data = [{"one": 0, "two": ts}] df = orig.copy() df.loc[1, :] = [np.nan, NaT] tm.assert_frame_equal(df, expected) def test_20476(): mi = MultiIndex.from_product([["A", "B"], ["a", "b", "c"]]) df = DataFrame(-1, index=range(3), columns=mi) filler = DataFrame([[1, 2, 3.0]] * 3, index=range(3), columns=["a", "b", "c"]) df["A"] = filler expected = DataFrame( { 0: [1, 1, 1], 1: [2, 2, 2], 2: [3.0, 3.0, 3.0], 3: [-1, -1, -1], 4: [-1, -1, -1], 5: [-1, -1, -1], } ) expected.columns = mi exp_dtypes = Series( [np.dtype(np.int64)] * 2 + [np.dtype(np.float64)] + [np.dtype(np.int64)] * 3, index=mi, ) tm.assert_series_equal(df.dtypes, exp_dtypes)
TestDataFrameSetitemCoercion
python
Pylons__pyramid
tests/test_renderers.py
{ "start": 4674, "end": 15950 }
class ____(unittest.TestCase): def setUp(self): self.config = cleanUp() def tearDown(self): cleanUp() def _makeOne(self, *arg, **kw): from pyramid.renderers import RendererHelper return RendererHelper(*arg, **kw) def test_instance_conforms(self): from zope.interface.verify import verifyObject from pyramid.interfaces import IRendererInfo helper = self._makeOne() verifyObject(IRendererInfo, helper) def test_settings_registry_settings_is_None(self): class Dummy: settings = None helper = self._makeOne(registry=Dummy) self.assertEqual(helper.settings, {}) def test_settings_registry_name_is_None(self): class Dummy: settings = None helper = self._makeOne(registry=Dummy) self.assertEqual(helper.name, None) self.assertEqual(helper.type, '') def test_settings_registry_settings_is_not_None(self): class Dummy: settings = {'a': 1} helper = self._makeOne(registry=Dummy) self.assertEqual(helper.settings, {'a': 1}) def _registerRendererFactory(self): from pyramid.interfaces import IRendererFactory def renderer(*arg): def respond(*arg): return arg renderer.respond = respond return respond self.config.registry.registerUtility( renderer, IRendererFactory, name='.foo' ) return renderer def _registerResponseFactory(self): from pyramid.interfaces import IResponseFactory class ResponseFactory: pass self.config.registry.registerUtility( lambda r: ResponseFactory(), IResponseFactory ) def test_render_to_response(self): self._registerRendererFactory() self._registerResponseFactory() request = Dummy() helper = self._makeOne('loo.foo') response = helper.render_to_response('values', {}, request=request) self.assertEqual(response.app_iter[0], 'values') self.assertEqual(response.app_iter[1], {}) def test_get_renderer(self): factory = self._registerRendererFactory() helper = self._makeOne('loo.foo') self.assertEqual(helper.get_renderer(), factory.respond) def test_render_view(self): import pyramid.csrf self._registerRendererFactory() self._registerResponseFactory() request = Dummy() helper = self._makeOne('loo.foo') view = 'view' context = 'context' request = testing.DummyRequest() response = 'response' response = helper.render_view(request, response, view, context) get_csrf = response.app_iter[1].pop('get_csrf_token') self.assertEqual(get_csrf.args, (request,)) self.assertEqual(get_csrf.func, pyramid.csrf.get_csrf_token) self.assertEqual(response.app_iter[0], 'response') self.assertEqual( response.app_iter[1], { 'renderer_info': helper, 'renderer_name': 'loo.foo', 'request': request, 'context': 'context', 'view': 'view', 'req': request, }, ) def test_render_explicit_registry(self): factory = self._registerRendererFactory() class DummyRegistry: def __init__(self): self.responses = [factory, lambda *arg: {}, None] def queryUtility(self, iface, name=None): self.queried = True return self.responses.pop(0) def notify(self, event): self.event = event reg = DummyRegistry() helper = self._makeOne('loo.foo', registry=reg) result = helper.render('value', {}) self.assertEqual(result[0], 'value') self.assertEqual(result[1], {}) self.assertTrue(reg.queried) self.assertEqual(reg.event, {}) self.assertEqual(reg.event.__class__.__name__, 'BeforeRender') def test_render_system_values_is_None(self): import pyramid.csrf self._registerRendererFactory() request = Dummy() context = Dummy() request.context = context helper = self._makeOne('loo.foo') result = helper.render('values', None, request=request) get_csrf = result[1].pop('get_csrf_token') self.assertEqual(get_csrf.args, (request,)) self.assertEqual(get_csrf.func, pyramid.csrf.get_csrf_token) system = { 'request': request, 'context': context, 'renderer_name': 'loo.foo', 'view': None, 'renderer_info': helper, 'req': request, } self.assertEqual(result[0], 'values') self.assertEqual(result[1], system) def test__make_response_request_is_None(self): request = None helper = self._makeOne('loo.foo') response = helper._make_response('abc', request) self.assertEqual(response.body, b'abc') def test__make_response_request_is_None_response_factory_exists(self): self._registerResponseFactory() request = None helper = self._makeOne('loo.foo') response = helper._make_response(b'abc', request) self.assertEqual(response.__class__.__name__, 'ResponseFactory') self.assertEqual(response.body, b'abc') def test__make_response_result_is_unicode(self): from pyramid.response import Response request = testing.DummyRequest() request.response = Response() helper = self._makeOne('loo.foo') la = text_('/La Pe\xc3\xb1a', 'utf-8') response = helper._make_response(la, request) self.assertEqual(response.body, la.encode('utf-8')) def test__make_response_result_is_str(self): from pyramid.response import Response request = testing.DummyRequest() request.response = Response() helper = self._makeOne('loo.foo') la = text_('/La Pe\xc3\xb1a', 'utf-8') response = helper._make_response(la.encode('utf-8'), request) self.assertEqual(response.body, la.encode('utf-8')) def test__make_response_result_is_iterable(self): from pyramid.response import Response request = testing.DummyRequest() request.response = Response() helper = self._makeOne('loo.foo') la = text_('/La Pe\xc3\xb1a', 'utf-8') response = helper._make_response([la.encode('utf-8')], request) self.assertEqual(response.body, la.encode('utf-8')) def test__make_response_result_is_other(self): self._registerResponseFactory() request = None helper = self._makeOne('loo.foo') result = object() response = helper._make_response(result, request) self.assertEqual(response.body, result) def test__make_response_result_is_None_no_body(self): from pyramid.response import Response request = testing.DummyRequest() request.response = Response() helper = self._makeOne('loo.foo') response = helper._make_response(None, request) self.assertEqual(response.body, b'') def test__make_response_result_is_None_existing_body_not_molested(self): from pyramid.response import Response request = testing.DummyRequest() response = Response() response.body = b'abc' request.response = response helper = self._makeOne('loo.foo') response = helper._make_response(None, request) self.assertEqual(response.body, b'abc') def test_with_alternate_response_factory(self): from pyramid.interfaces import IResponseFactory class ResponseFactory: def __init__(self): pass self.config.registry.registerUtility( lambda r: ResponseFactory(), IResponseFactory ) request = testing.DummyRequest() helper = self._makeOne('loo.foo') response = helper._make_response(b'abc', request) self.assertEqual(response.__class__, ResponseFactory) self.assertEqual(response.body, b'abc') def test__make_response_with_real_request(self): # functional from pyramid.request import Request request = Request({}) request.registry = self.config.registry request.response.status = '406 You Lose' helper = self._makeOne('loo.foo') response = helper._make_response('abc', request) self.assertEqual(response.status, '406 You Lose') self.assertEqual(response.body, b'abc') def test_clone_noargs(self): helper = self._makeOne('name', 'package', 'registry') cloned_helper = helper.clone() self.assertEqual(cloned_helper.name, 'name') self.assertEqual(cloned_helper.package, 'package') self.assertEqual(cloned_helper.registry, 'registry') self.assertFalse(helper is cloned_helper) def test_clone_allargs(self): helper = self._makeOne('name', 'package', 'registry') cloned_helper = helper.clone( name='name2', package='package2', registry='registry2' ) self.assertEqual(cloned_helper.name, 'name2') self.assertEqual(cloned_helper.package, 'package2') self.assertEqual(cloned_helper.registry, 'registry2') self.assertFalse(helper is cloned_helper) def test_renderer_absolute_file(self): registry = self.config.registry settings = {} registry.settings = settings import os from pyramid.interfaces import IRendererFactory here = os.path.dirname(os.path.abspath(__file__)) fixture = os.path.join(here, 'fixtures/minimal.pt') def factory(info, **kw): return info self.config.registry.registerUtility( factory, IRendererFactory, name='.pt' ) result = self._makeOne(fixture).renderer self.assertEqual(result.registry, registry) self.assertEqual(result.type, '.pt') self.assertEqual(result.package, None) self.assertEqual(result.name, fixture) self.assertEqual(result.settings, settings) def test_renderer_with_package(self): import pyramid registry = self.config.registry settings = {} registry.settings = settings import os from pyramid.interfaces import IRendererFactory here = os.path.dirname(os.path.abspath(__file__)) fixture = os.path.join(here, 'fixtures/minimal.pt') def factory(info, **kw): return info self.config.registry.registerUtility( factory, IRendererFactory, name='.pt' ) result = self._makeOne(fixture, pyramid).renderer self.assertEqual(result.registry, registry) self.assertEqual(result.type, '.pt') self.assertEqual(result.package, pyramid) self.assertEqual(result.name, fixture) self.assertEqual(result.settings, settings) def test_renderer_missing(self): inst = self._makeOne('foo') self.assertRaises(ValueError, getattr, inst, 'renderer')
TestRendererHelper
python
encode__django-rest-framework
tests/test_throttling.py
{ "start": 16288, "end": 16890 }
class ____(TestCase): def setUp(self): self.throttle = AnonRateThrottle() def test_authenticated_user_not_affected(self): request = Request(HttpRequest()) user = User.objects.create(username='test') force_authenticate(request, user) request.user = user assert self.throttle.get_cache_key(request, view={}) is None def test_get_cache_key_returns_correct_value(self): request = Request(HttpRequest()) cache_key = self.throttle.get_cache_key(request, view={}) assert cache_key == 'throttle_anon_None'
AnonRateThrottleTests
python
pypa__warehouse
warehouse/organizations/models.py
{ "start": 29609, "end": 29669 }
class ____(str, enum.Enum): Member = "Member"
TeamRoleType
python
scikit-learn__scikit-learn
sklearn/_loss/loss.py
{ "start": 27603, "end": 29955 }
class ____(BaseLoss): """Half Tweedie deviance loss with log-link, for regression. Domain: y_true in real numbers for power <= 0 y_true in non-negative real numbers for 0 < power < 2 y_true in positive real numbers for 2 <= power y_pred in positive real numbers power in real numbers Link: y_pred = exp(raw_prediction) For a given sample x_i, half Tweedie deviance loss with p=power is defined as:: loss(x_i) = max(y_true_i, 0)**(2-p) / (1-p) / (2-p) - y_true_i * exp(raw_prediction_i)**(1-p) / (1-p) + exp(raw_prediction_i)**(2-p) / (2-p) Taking the limits for p=0, 1, 2 gives HalfSquaredError with a log link, HalfPoissonLoss and HalfGammaLoss. We also skip constant terms, but those are different for p=0, 1, 2. Therefore, the loss is not continuous in `power`. Note furthermore that although no Tweedie distribution exists for 0 < power < 1, it still gives a strictly consistent scoring function for the expectation. """ def __init__(self, sample_weight=None, power=1.5): super().__init__( closs=CyHalfTweedieLoss(power=float(power)), link=LogLink(), ) if self.closs.power <= 0: self.interval_y_true = Interval(-np.inf, np.inf, False, False) elif self.closs.power < 2: self.interval_y_true = Interval(0, np.inf, True, False) else: self.interval_y_true = Interval(0, np.inf, False, False) def constant_to_optimal_zero(self, y_true, sample_weight=None): if self.closs.power == 0: return HalfSquaredError().constant_to_optimal_zero( y_true=y_true, sample_weight=sample_weight ) elif self.closs.power == 1: return HalfPoissonLoss().constant_to_optimal_zero( y_true=y_true, sample_weight=sample_weight ) elif self.closs.power == 2: return HalfGammaLoss().constant_to_optimal_zero( y_true=y_true, sample_weight=sample_weight ) else: p = self.closs.power term = np.power(np.maximum(y_true, 0), 2 - p) / (1 - p) / (2 - p) if sample_weight is not None: term *= sample_weight return term
HalfTweedieLoss
python
openai__openai-python
src/openai/resources/vector_stores/vector_stores.py
{ "start": 34352, "end": 35451 }
class ____: def __init__(self, vector_stores: AsyncVectorStores) -> None: self._vector_stores = vector_stores self.create = async_to_streamed_response_wrapper( vector_stores.create, ) self.retrieve = async_to_streamed_response_wrapper( vector_stores.retrieve, ) self.update = async_to_streamed_response_wrapper( vector_stores.update, ) self.list = async_to_streamed_response_wrapper( vector_stores.list, ) self.delete = async_to_streamed_response_wrapper( vector_stores.delete, ) self.search = async_to_streamed_response_wrapper( vector_stores.search, ) @cached_property def files(self) -> AsyncFilesWithStreamingResponse: return AsyncFilesWithStreamingResponse(self._vector_stores.files) @cached_property def file_batches(self) -> AsyncFileBatchesWithStreamingResponse: return AsyncFileBatchesWithStreamingResponse(self._vector_stores.file_batches)
AsyncVectorStoresWithStreamingResponse
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/large_concat_op_test.py
{ "start": 908, "end": 1580 }
class ____(test.TestCase): """Tests that belong in concat_op_test.py, but run over large tensors.""" def testConcatLargeTensors(self): # CPU-only test, because it fails on GPUs with <= 4GB memory. with ops.device("/cpu:0"): a = array_ops.ones([2**31 + 6], dtype=dtypes.int8) b = array_ops.zeros([1024], dtype=dtypes.int8) onezeros = array_ops.concat([a, b], 0) with self.session(use_gpu=False): # TODO(dga): Add more depth to this test to validate correctness, # not just non-crashingness, once other large tensor fixes have gone in. _ = self.evaluate(onezeros) if __name__ == "__main__": test.main()
LargeConcatOpTest
python
pola-rs__polars
py-polars/src/polars/io/iceberg/dataset.py
{ "start": 19553, "end": 22251 }
class ____(_ResolvedScanDataBase): """Resolved parameters for reading via PyIceberg.""" # We're not interested in inspecting anything for the pyiceberg scan, so # this class is just a wrapper. lf: pl.LazyFrame _snapshot_id_key: str def to_lazyframe(self) -> pl.LazyFrame: return self.lf @property def snapshot_id_key(self) -> str: return self._snapshot_id_key def _redact_dict_values(obj: Any) -> Any: return ( dict.fromkeys(obj.keys(), "REDACTED") if isinstance(obj, dict) else f"<{type(obj).__name__} object>" if obj is not None else "None" ) def _convert_iceberg_to_object_store_storage_options( iceberg_storage_properties: dict[str, str], ) -> dict[str, str]: storage_options = {} for k, v in iceberg_storage_properties.items(): if ( translated_key := ICEBERG_TO_OBJECT_STORE_CONFIG_KEY_MAP.get(k) ) is not None: storage_options[translated_key] = v elif "." not in k: # Pass-through non-Iceberg config keys, as they may be native config # keys. We identify Iceberg keys by checking for a dot - from # observation nearly all Iceberg config keys contain dots, whereas # native config keys do not contain them. storage_options[k] = v # Otherwise, unknown keys are ignored / not passed. This is to avoid # interfering with credential provider auto-init, which bails on # unknown keys. return storage_options # https://py.iceberg.apache.org/configuration/#fileio # This does not contain all keys - some have no object-store equivalent. ICEBERG_TO_OBJECT_STORE_CONFIG_KEY_MAP: dict[str, str] = { # S3 "s3.endpoint": "aws_endpoint_url", "s3.access-key-id": "aws_access_key_id", "s3.secret-access-key": "aws_secret_access_key", "s3.session-token": "aws_session_token", "s3.region": "aws_region", "s3.proxy-uri": "proxy_url", "s3.connect-timeout": "connect_timeout", "s3.request-timeout": "timeout", "s3.force-virtual-addressing": "aws_virtual_hosted_style_request", # Azure "adls.account-name": "azure_storage_account_name", "adls.account-key": "azure_storage_account_key", "adls.sas-token": "azure_storage_sas_key", "adls.tenant-id": "azure_storage_tenant_id", "adls.client-id": "azure_storage_client_id", "adls.client-secret": "azure_storage_client_secret", "adls.account-host": "azure_storage_authority_host", "adls.token": "azure_storage_token", # Google storage "gcs.oauth2.token": "bearer_token", # HuggingFace "hf.token": "token", }
_PyIcebergScanData
python
run-llama__llama_index
llama-index-integrations/storage/index_store/llama-index-storage-index-store-gel/llama_index/storage/index_store/gel/base.py
{ "start": 167, "end": 685 }
class ____(KVIndexStore): """ Gel Index store. Args: gel_kvstore (GelKVStore): Gel key-value store namespace (str): namespace for the index store """ def __init__( self, gel_kvstore: GelKVStore, namespace: Optional[str] = None, collection_suffix: Optional[str] = None, ) -> None: """Init a GelIndexStore.""" super().__init__( gel_kvstore, namespace=namespace, collection_suffix=collection_suffix )
GelIndexStore
python
joke2k__faker
faker/providers/bank/fr_FR/__init__.py
{ "start": 42, "end": 197 }
class ____(BankProvider): """Implement bank provider for ``fr_FR`` locale.""" bban_format = "#######################" country_code = "FR"
Provider
python
pandas-dev__pandas
asv_bench/benchmarks/frame_ctor.py
{ "start": 2310, "end": 2751 }
class ____: params = [None, 1000] param_names = ["nrows"] # Generators get exhausted on use, so run setup before every call number = 1 repeat = (3, 250, 10) def setup(self, nrows): N = 100000 self.gen = ((x, (x * 20), (x * 100)) for x in range(N)) def time_frame_from_records_generator(self, nrows): # issue-6700 self.df = DataFrame.from_records(self.gen, nrows=nrows)
FromRecords
python
allegroai__clearml
clearml/backend_api/services/v2_23/projects.py
{ "start": 140119, "end": 141262 }
class ____(Response): """ Response of projects.make_public endpoint. :param updated: Number of projects updated :type updated: int """ _service = "projects" _action = "make_public" _version = "2.23" _schema = { "definitions": {}, "properties": { "updated": { "description": "Number of projects updated", "type": ["integer", "null"], } }, "type": "object", } def __init__(self, updated: Optional[int] = None, **kwargs: Any) -> None: super(MakePublicResponse, self).__init__(**kwargs) self.updated = updated @schema_property("updated") def updated(self) -> Optional[int]: return self._property_updated @updated.setter def updated(self, value: Optional[int]) -> None: if value is None: self._property_updated = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "updated", six.integer_types) self._property_updated = value
MakePublicResponse
python
mlflow__mlflow
mlflow/openai/model.py
{ "start": 23884, "end": 31486 }
class ____: def __init__(self, model): task = model.pop("task") if task not in _PYFUNC_SUPPORTED_TASKS: raise mlflow.MlflowException.invalid_parameter_value( f"Unsupported task: {task}. Supported tasks: {_PYFUNC_SUPPORTED_TASKS}." ) self.model = model self.task = task self.api_config = _get_api_config() self.api_token = _OAITokenHolder(self.api_config.api_type) if self.task != "embeddings": self._setup_completions() def get_raw_model(self): """ Returns the underlying model. """ return self.model def _setup_completions(self): if self.task == "chat.completions": self.template = self.model.get("messages", []) else: self.template = self.model.get("prompt") self.formatter = _ContentFormatter(self.task, self.template) def format_completions(self, params_list): return [self.formatter.format(**params) for params in params_list] def get_params_list(self, data): if len(self.formatter.variables) == 1: variable = self.formatter.variables[0] if variable in data.columns: return data[[variable]].to_dict(orient="records") else: first_string_column = _first_string_column(data) return [{variable: s} for s in data[first_string_column]] else: return data[self.formatter.variables].to_dict(orient="records") def get_client(self, max_retries: int, timeout: float): # with_option method should not be used before v1.3.8: https://github.com/openai/openai-python/issues/865 if self.api_config.api_type in ("azure", "azure_ad", "azuread"): from openai import AzureOpenAI return AzureOpenAI( api_key=self.api_token.token, azure_endpoint=self.api_config.api_base, api_version=self.api_config.api_version, azure_deployment=self.api_config.deployment_id, max_retries=max_retries, timeout=timeout, ) else: from openai import OpenAI return OpenAI( api_key=self.api_token.token, base_url=self.api_config.api_base, max_retries=max_retries, timeout=timeout, ) def _predict_chat(self, data, params): from mlflow.openai.api_request_parallel_processor import process_api_requests _validate_model_params(self.task, self.model, params) max_retries = params.pop("max_retries", self.api_config.max_retries) timeout = params.pop("timeout", self.api_config.timeout) messages_list = self.format_completions(self.get_params_list(data)) client = self.get_client(max_retries=max_retries, timeout=timeout) requests = [ partial( client.chat.completions.create, messages=messages, model=self.model["model"], **params, ) for messages in messages_list ] results = process_api_requests(request_tasks=requests) return [r.choices[0].message.content for r in results] def _predict_completions(self, data, params): from mlflow.openai.api_request_parallel_processor import process_api_requests _validate_model_params(self.task, self.model, params) prompts_list = self.format_completions(self.get_params_list(data)) max_retries = params.pop("max_retries", self.api_config.max_retries) timeout = params.pop("timeout", self.api_config.timeout) batch_size = params.pop("batch_size", self.api_config.batch_size) _logger.debug(f"Requests are being batched by {batch_size} samples.") client = self.get_client(max_retries=max_retries, timeout=timeout) requests = [ partial( client.completions.create, prompt=prompts_list[i : i + batch_size], model=self.model["model"], **params, ) for i in range(0, len(prompts_list), batch_size) ] results = process_api_requests(request_tasks=requests) return [row.text for batch in results for row in batch.choices] def _predict_embeddings(self, data, params): from mlflow.openai.api_request_parallel_processor import process_api_requests _validate_model_params(self.task, self.model, params) max_retries = params.pop("max_retries", self.api_config.max_retries) timeout = params.pop("timeout", self.api_config.timeout) batch_size = params.pop("batch_size", self.api_config.batch_size) _logger.debug(f"Requests are being batched by {batch_size} samples.") first_string_column = _first_string_column(data) texts = data[first_string_column].tolist() client = self.get_client(max_retries=max_retries, timeout=timeout) requests = [ partial( client.embeddings.create, input=texts[i : i + batch_size], model=self.model["model"], **params, ) for i in range(0, len(texts), batch_size) ] results = process_api_requests(request_tasks=requests) return [row.embedding for batch in results for row in batch.data] def predict(self, data, params: dict[str, Any] | None = None): """ Args: data: Model input data. params: Additional parameters to pass to the model for inference. Returns: Model predictions. """ self.api_token.refresh() if self.task == "chat.completions": return self._predict_chat(data, params or {}) elif self.task == "completions": return self._predict_completions(data, params or {}) elif self.task == "embeddings": return self._predict_embeddings(data, params or {}) def _load_pyfunc(path): """Loads PyFunc implementation. Called by ``pyfunc.load_model``. Args: path: Local filesystem path to the MLflow Model with the ``openai`` flavor. """ return _OpenAIWrapper(_load_model(path)) def load_model(model_uri, dst_path=None): """ Load an OpenAI model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` - ``runs:/<mlflow_run_id>/run-relative/path/to/model`` For more information about supported URI schemes, see `Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html# artifact-locations>`_. dst_path: The local filesystem path to which to download the model artifact. This directory must already exist. If unspecified, a local output path will be created. Returns: A dictionary representing the OpenAI model. """ local_model_path = _download_artifact_from_uri(artifact_uri=model_uri, output_path=dst_path) flavor_conf = _get_flavor_configuration(local_model_path, FLAVOR_NAME) _add_code_from_conf_to_system_path(local_model_path, flavor_conf) model_data_path = os.path.join(local_model_path, flavor_conf.get("data", MODEL_FILENAME)) return _load_model(model_data_path)
_OpenAIWrapper
python
openai__openai-python
src/openai/types/image_edit_params.py
{ "start": 4704, "end": 5008 }
class ____(ImageEditParamsBase, total=False): stream: Optional[Literal[False]] """Edit the image in streaming mode. Defaults to `false`. See the [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information. """
ImageEditParamsNonStreaming
python
kamyu104__LeetCode-Solutions
Python/count-unguarded-cells-in-the-grid.py
{ "start": 76, "end": 872 }
class ____(object): def countUnguarded(self, m, n, guards, walls): """ :type m: int :type n: int :type guards: List[List[int]] :type walls: List[List[int]] :rtype: int """ DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)] GREEN, RED, BLOCK = range(3) grid = [[GREEN]*n for _ in xrange(m)] for r, c in itertools.chain(guards, walls): grid[r][c] = BLOCK for r, c in guards: for dr, dc in DIRECTIONS: nr, nc = r+dr, c+dc while 0 <= nr < m and 0 <= nc < n and grid[nr][nc] != BLOCK: grid[nr][nc] = RED nr, nc = nr+dr, nc+dc return sum(grid[r][c] == GREEN for r in xrange(m) for c in xrange(n))
Solution
python
django__django
django/db/backends/postgresql/compiler.py
{ "start": 581, "end": 2310 }
class ____(BaseSQLInsertCompiler): def assemble_as_sql(self, fields, value_rows): # Specialize bulk-insertion of literal values through UNNEST to # reduce the time spent planning the query. if ( # The optimization is not worth doing if there is a single # row as it will result in the same number of placeholders. len(value_rows) <= 1 # Lack of fields denote the usage of the DEFAULT keyword # for the insertion of empty rows. or any(field is None for field in fields) # Field.get_placeholder takes value as an argument, so the # resulting placeholder might be dependent on the value. # in UNNEST requires a single placeholder to "fit all values" in # the array. or any(hasattr(field, "get_placeholder") for field in fields) # Fields that don't use standard internal types might not be # unnest'able (e.g. array and geometry types are known to be # problematic). or any( (field.target_field if field.is_relation else field).get_internal_type() not in self.connection.data_types for field in fields ) # Compilable cannot be combined in an array of literal values. or any(any(hasattr(value, "as_sql") for value in row) for row in value_rows) ): return super().assemble_as_sql(fields, value_rows) db_types = [field.db_type(self.connection) for field in fields] return InsertUnnest(["(%%s)::%s[]" % db_type for db_type in db_types]), [ list(map(list, zip(*value_rows))) ]
SQLInsertCompiler
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/test_organization_alertrule_detector.py
{ "start": 1590, "end": 5143 }
class ____(OrganizationAlertRuleDetectorAPITestCase): def test_get_with_detector_id_filter(self) -> None: response = self.get_success_response( self.organization.slug, detector_id=str(self.detector_1.id) ) assert response.data == serialize(self.alert_rule_detector_1, self.user) def test_get_with_alert_rule_id_filter(self) -> None: response = self.get_success_response(self.organization.slug, alert_rule_id="12345") assert response.data["alertRuleId"] == "12345" assert response.data["ruleId"] is None assert response.data["detectorId"] == str(self.detector_1.id) def test_get_with_rule_id_filter(self) -> None: response = self.get_success_response(self.organization.slug, rule_id="67890") assert response.data["ruleId"] == "67890" assert response.data["alertRuleId"] is None assert response.data["detectorId"] == str(self.detector_2.id) def test_get_with_multiple_filters(self) -> None: response = self.get_success_response( self.organization.slug, detector_id=str(self.detector_1.id), alert_rule_id="12345", ) assert response.data == serialize(self.alert_rule_detector_1, self.user) def test_get_with_multiple_filters_with_invalid_filter(self) -> None: self.get_error_response( self.organization.slug, detector_id=str(self.detector_1.id), alert_rule_id="this is not a valid ID", ) def test_get_with_nonexistent_detector_id(self) -> None: self.get_error_response(self.organization.slug, detector_id="99999", status_code=404) def test_get_with_nonexistent_alert_rule_id(self) -> None: self.get_error_response(self.organization.slug, alert_rule_id="99999", status_code=404) def test_get_with_nonexistent_rule_id(self) -> None: self.get_error_response(self.organization.slug, rule_id="99999", status_code=404) def test_organization_isolation(self) -> None: self.get_error_response( self.organization.slug, detector_id=str(self.other_detector.id), status_code=404 ) def test_get_without_any_filter(self) -> None: self.get_error_response(self.organization.slug, status_code=400) def test_fallback_with_fake_alert_rule_id(self) -> None: """ Test that when an alert rule doesn't exist, the endpoint falls back to looking up the Detector by subtracting 10^9 from the alert_rule_id. """ # Create a detector with no AlertRuleDetector mapping detector = self.create_detector(project=self.project) # Calculate the fake alert_rule_id fake_alert_rule_id = get_fake_id_from_object_id(detector.id) # Query using the fake alert_rule_id response = self.get_success_response( self.organization.slug, alert_rule_id=str(fake_alert_rule_id) ) # Should return a fake AlertRuleDetector response assert response.data == { "detectorId": str(detector.id), "alertRuleId": str(fake_alert_rule_id), "ruleId": None, } def test_fallback_with_nonexistent_detector(self) -> None: # Use a fake alert_rule_id that won't map to any real detector nonexistent_fake_id = get_fake_id_from_object_id(999999) self.get_error_response( self.organization.slug, alert_rule_id=str(nonexistent_fake_id), status_code=404 )
OrganizationAlertRuleDetectorIndexGetTest
python
realpython__materials
python-magic-methods/number.py
{ "start": 0, "end": 647 }
class ____: def __init__(self, value): self.value = value def __add__(self, other): print("__add__ called") if isinstance(other, Number): return Number(self.value + other.value) elif isinstance(other, int | float): return Number(self.value + other) else: raise TypeError("unsupported operand type for +") def __radd__(self, other): print("__radd__ called") return self.__add__(other) def __iadd__(self, other): print("__iadd__ called") return self.__add__(other) def __str__(self): return str(self.value)
Number
python
getsentry__sentry
tests/sentry/models/test_commitfilechange.py
{ "start": 194, "end": 929 }
class ____(TestCase): def test_get_count_for_commits(self) -> None: group = self.create_group() organization_id = group.organization.id repo = Repository.objects.create(name="example", organization_id=organization_id) commit = Commit.objects.create( key="a" * 40, repository_id=repo.id, organization_id=organization_id, message=f"Foo Biz\n\nFixes {group.qualified_short_id}", ) CommitFileChange.objects.create( organization_id=organization_id, commit_id=commit.id, filename=".gitignore", type="M" ) count = CommitFileChange.objects.get_count_for_commits([commit]) assert count == 1
CommitFileChangeTest
python
getsentry__sentry
tests/acceptance/test_organization_alert_rules.py
{ "start": 393, "end": 2422 }
class ____(AcceptanceTestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.login_as(self.user) self.path = f"/organizations/{self.organization.slug}/alerts/rules/" def test_empty_alert_rules(self) -> None: with self.feature(FEATURE_NAME): self.browser.get(self.path) self.browser.wait_until_not('[data-test-id="loading-indicator"]') def test_alert_rules_list(self) -> None: Rule.objects.filter(project=self.project).update(date_added=timezone.now()) self.create_alert_rule( name="My Alert Rule", date_added=timezone.now(), user=self.user, ) with self.feature(FEATURE_NAME): self.browser.get(self.path) self.browser.wait_until_not('[data-test-id="loading-indicator"]') def test_alert_rules_alert_list(self) -> None: self.create_alert_rule( name="My Alert Rule", projects=[self.project], date_added=timezone.now(), user=self.user, ) alert_rule_critical = self.create_alert_rule( organization=self.organization, projects=[self.project], name="some rule [crit]", query="", aggregate="count()", time_window=1, threshold_type=AlertRuleThresholdType.ABOVE, resolve_threshold=10, threshold_period=1, ) trigger = self.create_alert_rule_trigger( alert_rule=alert_rule_critical, alert_threshold=100 ) crit_incident = self.create_incident(status=20, alert_rule=alert_rule_critical) IncidentTrigger.objects.create( incident=crit_incident, alert_rule_trigger=trigger, status=TriggerStatus.ACTIVE.value ) with self.feature(["organizations:incidents"]): self.browser.get(self.path) self.browser.wait_until_not('[data-test-id="loading-indicator"]')
OrganizationAlertRulesListTest
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 33164, "end": 34518 }
class ____( _MutableDictTestBase, fixtures.MappedTest ): @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("data", PickleType), Column("non_mutable_data", PickleType), Column("unrelated_data", String(50)), ) Table( "subfoo", metadata, Column("id", Integer, ForeignKey("foo.id"), primary_key=True), ) def setup_mappers(cls): foo = cls.tables.foo subfoo = cls.tables.subfoo cls.mapper_registry.map_imperatively(Foo, foo) cls.mapper_registry.map_imperatively(SubFoo, subfoo, inherits=Foo) MutableDict.associate_with_attribute(Foo.data) def test_in_place_mutation(self): sess = fixture_session() f1 = SubFoo(data={"a": "b"}) sess.add(f1) sess.commit() f1.data["a"] = "c" sess.commit() eq_(f1.data, {"a": "c"}) def test_replace(self): sess = fixture_session() f1 = SubFoo(data={"a": "b"}) sess.add(f1) sess.flush() f1.data = {"b": "c"} sess.commit() eq_(f1.data, {"b": "c"})
MutableAssocWithAttrInheritTest
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/integrations/tableau/customize_upstream_dependencies.py
{ "start": 625, "end": 1445 }
class ____(DagsterTableauTranslator): def get_asset_spec(self, data: TableauTranslatorData) -> dg.AssetSpec: # We create the default asset spec using super() default_spec = super().get_asset_spec(data) # We customize upstream dependencies for the Tableau sheet named `my_tableau_sheet` return default_spec.replace_attributes( deps=["my_upstream_asset"] if data.content_type == TableauContentType.SHEET and data.properties.get("name") == "my_tableau_sheet" else ... ) tableau_specs = load_tableau_asset_specs( tableau_workspace, dagster_tableau_translator=MyCustomTableauTranslator(), ) # end_upstream_asset defs = dg.Definitions(assets=[*tableau_specs], resources={"tableau": tableau_workspace})
MyCustomTableauTranslator
python
Lightning-AI__lightning
tests/tests_pytorch/checkpointing/test_model_checkpoint.py
{ "start": 42385, "end": 42518 }
class ____(Callback): def on_train_end(self, trainer, pl_module): raise RuntimeError("Trouble!")
TroubledCallbackOnTrainEnd
python
apache__airflow
kubernetes-tests/tests/kubernetes_tests/test_kubernetes_pod_operator.py
{ "start": 58813, "end": 60620 }
class ____(BaseK8STest): @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): """Create kubernetes_default connection""" connection = Connection( conn_id="kubernetes_default", conn_type="kubernetes", ) create_connection_without_db(connection) @pytest.mark.parametrize( ("active_deadline_seconds", "should_fail"), [(3, True), (60, False)], ids=["should_fail", "should_not_fail"], ) def test_kubernetes_pod_operator_active_deadline_seconds(self, active_deadline_seconds, should_fail): ns = "default" echo = "echo 'hello world'" if should_fail: echo += " && sleep 10" k = KubernetesPodOperator( task_id=f"test_task_{active_deadline_seconds}", active_deadline_seconds=active_deadline_seconds, image="busybox", cmds=["sh", "-c", echo], namespace=ns, on_finish_action="keep_pod", ) context = create_context(k) ctx_manager = pytest.raises(AirflowException) if should_fail else nullcontext() with ctx_manager: k.execute(context) pod = k.find_pod(ns, context, exclude_checked=False) k8s_client = client.CoreV1Api() pod_status = k8s_client.read_namespaced_pod_status(name=pod.metadata.name, namespace=ns) phase = pod_status.status.phase reason = pod_status.status.reason if should_fail: expected_phase = "Failed" expected_reason = "DeadlineExceeded" else: expected_phase = "Succeeded" expected_reason = None assert phase == expected_phase assert reason == expected_reason
TestKubernetesPodOperator
python
wandb__wandb
wandb/_pydantic/base.py
{ "start": 1616, "end": 1754 }
class ____(PydanticCompatMixin, BaseModel): __doc__ = None # Prevent subclasses from inheriting the BaseModel docstring
CompatBaseModel
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 29922, "end": 30199 }
class ____(torch.nn.Module): def __init__(self): super().__init__() self.layer = torch.nn.Linear(4, 4) self.step = 10 def forward(self, x: torch.Tensor) -> torch.Tensor: x = x + 1 return self.layer(x) + self.step
ModuleWithIntAttr
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 16528, "end": 17153 }
class ____(RenderedComponentContent): def __init__(self, markdown, styling=None, content_block_type="markdown") -> None: super().__init__(content_block_type=content_block_type, styling=styling) self.markdown = markdown @override def to_json_dict(self) -> dict[str, JSONValues]: """Returns a JSON-serializable dict representation of this RenderedMarkdownContent. Returns: A JSON-serializable dict representation of this RenderedMarkdownContent. """ d = super().to_json_dict() d["markdown"] = self.markdown return d
RenderedMarkdownContent
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/black/cases/type_params.py
{ "start": 53, "end": 671 }
class ____[ T ] : pass def all_in[T : int,U : (bytes, str),* Ts,**P](): pass def really_long[WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine](): pass def even_longer[WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine: WhatIfItHadABound](): pass def it_gets_worse[WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine, ItCouldBeGenericOverMultipleTypeVars](): pass def magic[Trailing, Comma,](): pass def weird_syntax[T: lambda: 42, U: a or b](): pass def name_3[name_0: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa if aaaaaaaaaaa else name_3](): pass
C
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_kubernetes_engine.py
{ "start": 4545, "end": 5117 }
class ____: def setup_method(self): self.gke_hook = GKEHook(location=GKE_ZONE) @mock.patch(GKE_STRING.format("GKEHook.get_credentials")) @mock.patch(GKE_STRING.format("ClusterManagerClient")) def test_gke_cluster_client_creation(self, mock_client, mock_get_creds): result = self.gke_hook.get_cluster_manager_client() mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) assert mock_client.return_value == result assert self.gke_hook._client == result
TestGKEHookClient
python
pandas-dev__pandas
asv_bench/benchmarks/gil.py
{ "start": 5390, "end": 6530 }
class ____: params = ["median", "mean", "min", "max", "var", "skew", "kurt", "std"] param_names = ["method"] def setup(self, method): win = 100 arr = np.random.rand(100000) if hasattr(DataFrame, "rolling"): df = DataFrame(arr).rolling(win) @run_parallel(num_threads=2) def parallel_rolling(): getattr(df, method)() self.parallel_rolling = parallel_rolling elif have_rolling_methods: rolling = { "median": rolling_median, "mean": rolling_mean, "min": rolling_min, "max": rolling_max, "var": rolling_var, "skew": rolling_skew, "kurt": rolling_kurt, "std": rolling_std, } @run_parallel(num_threads=2) def parallel_rolling(): rolling[method](arr, win) self.parallel_rolling = parallel_rolling else: raise NotImplementedError def time_rolling(self, method): self.parallel_rolling()
ParallelRolling
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py
{ "start": 17581, "end": 22786 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Qwen2_5OmniThinkerForConditionalGeneration`]. It is used to instantiate an Qwen2.5-Omni-Thinker model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Qwen2.5-Omni-Thinker. e.g. [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: audio_config (`dict`, *optional*): The config dictionary of the audio backbone. vision_config (`dict`, *optional*): The config dictionary of the vision backbone. text_config (`dict`, *optional*): The config dictionary of the text backbone. audio_token_index (`int`, *optional*, defaults to 151646): The audio token index to encode the audio prompt. image_token_index (`int`, *optional*, defaults to 151655): The image token index to encode the image prompt. video_token_index (`int`, *optional*, defaults to 151656): The video token index to encode the video prompt. position_id_per_seconds (`int`, *optional*, defaults to 25): The increment of position id per second. seconds_per_chunk (`int`, *optional*, defaults to 2): The duration in seconds of the chunk of audio and video data. audio_start_token_id (`int`, *optional*, defaults to 151647): The audio start token index to encode the audio prompt. audio_end_token_id (`int`, *optional*, defaults to 151648): The audio end token index to encode the audio prompt. user_token_id (`int, *optional*, defaults to 872): The user token index to encode the user token. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. Example: ```python >>> from transformers import Qwen2_5OmniThinkerForConditionalGeneration, Qwen2_5OmniThinkerConfig, Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniVisionEncoderConfig >>> # Initializing a Qwen2_5OmniAudioEncoder config >>> audio_config = Qwen2_5OmniAudioEncoderConfig() >>> # Initializing a Qwen2_5OmniVisionEncoder config >>> vision_config = Qwen2_5OmniVisionEncoderConfig() >>> # Initializing a Qwen2_5OmniTextConfig config >>> text_config = Qwen2_5OmniTextConfig() >>> # Initializing a Qwen2.5OmniThinker configuration >>> configuration = Qwen2_5OmniThinkerConfig(audio_config, vision_config, text_config) >>> # Initializing a model from the Qwen-Omni style configuration >>> model = Qwen2_5OmniThinkerForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "qwen2_5_omni_thinker" attribute_map = { "image_token_id": "image_token_index", "video_token_id": "video_token_index", "audio_token_id": "audio_token_index", } sub_configs = { "audio_config": Qwen2_5OmniAudioEncoderConfig, "vision_config": Qwen2_5OmniVisionEncoderConfig, "text_config": Qwen2_5OmniTextConfig, } def __init__( self, audio_config=None, vision_config=None, text_config=None, audio_token_index=151646, image_token_index=151655, video_token_index=151656, position_id_per_seconds=25, seconds_per_chunk=2, audio_start_token_id=151647, audio_end_token_id=151648, user_token_id=872, initializer_range=0.02, **kwargs, ): self.audio_token_index = audio_token_index self.image_token_index = image_token_index self.video_token_index = video_token_index self.user_token_id = user_token_id self.position_id_per_seconds = position_id_per_seconds self.seconds_per_chunk = seconds_per_chunk self.audio_start_token_id = audio_start_token_id self.audio_end_token_id = audio_end_token_id self.initializer_range = initializer_range if isinstance(vision_config, dict): vision_config = Qwen2_5OmniVisionEncoderConfig(**vision_config) elif vision_config is None: vision_config = Qwen2_5OmniVisionEncoderConfig() self.vision_config = vision_config if isinstance(audio_config, dict): audio_config = Qwen2_5OmniAudioEncoderConfig(**audio_config) elif audio_config is None: audio_config = Qwen2_5OmniAudioEncoderConfig() self.audio_config = audio_config if isinstance(text_config, dict): text_config = Qwen2_5OmniTextConfig(**text_config) elif text_config is None: text_config = Qwen2_5OmniTextConfig() self.text_config = text_config super().__init__(**kwargs)
Qwen2_5OmniThinkerConfig
python
encode__django-rest-framework
tests/test_renderers.py
{ "start": 1847, "end": 2049 }
class ____(BaseRenderer): media_type = 'mock/renderera' format = "formata" def render(self, data, media_type=None, renderer_context=None): return RENDERER_A_SERIALIZER(data)
RendererA
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin_ini/pydantic_settings.py
{ "start": 65, "end": 686 }
class ____(BaseSettings): foo: str s = Settings() s = Settings(foo='test', _case_sensitive=True, _env_prefix='test__', _env_file='test') s = Settings(foo='test', _case_sensitive=1, _env_prefix=2, _env_file=3) # MYPY: error: Argument "_case_sensitive" to "Settings" has incompatible type "int"; expected "Optional[bool]" [arg-type] # MYPY: error: Argument "_env_prefix" to "Settings" has incompatible type "int"; expected "Optional[str]" [arg-type] # MYPY: error: Argument "_env_file" to "Settings" has incompatible type "int"; expected "Optional[Union[Path, str, Sequence[Union[Path, str]]]]" [arg-type]
Settings
python
pypa__pip
src/pip/_internal/metadata/importlib/_dists.py
{ "start": 3327, "end": 8420 }
class ____(BaseDistribution): def __init__( self, dist: importlib.metadata.Distribution, info_location: BasePath | None, installed_location: BasePath | None, ) -> None: self._dist = dist self._info_location = info_location self._installed_location = installed_location @classmethod def from_directory(cls, directory: str) -> BaseDistribution: info_location = pathlib.Path(directory) dist = importlib.metadata.Distribution.at(info_location) return cls(dist, info_location, info_location.parent) @classmethod def from_metadata_file_contents( cls, metadata_contents: bytes, filename: str, project_name: str, ) -> BaseDistribution: # Generate temp dir to contain the metadata file, and write the file contents. temp_dir = pathlib.Path( TempDirectory(kind="metadata", globally_managed=True).path ) metadata_path = temp_dir / "METADATA" metadata_path.write_bytes(metadata_contents) # Construct dist pointing to the newly created directory. dist = importlib.metadata.Distribution.at(metadata_path.parent) return cls(dist, metadata_path.parent, None) @classmethod def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution: try: with wheel.as_zipfile() as zf: dist = WheelDistribution.from_zipfile(zf, name, wheel.location) except zipfile.BadZipFile as e: raise InvalidWheel(wheel.location, name) from e return cls(dist, dist.info_location, pathlib.PurePosixPath(wheel.location)) @property def location(self) -> str | None: if self._info_location is None: return None return str(self._info_location.parent) @property def info_location(self) -> str | None: if self._info_location is None: return None return str(self._info_location) @property def installed_location(self) -> str | None: if self._installed_location is None: return None return normalize_path(str(self._installed_location)) @property def canonical_name(self) -> NormalizedName: return get_dist_canonical_name(self._dist) @property def version(self) -> Version: try: version = ( parse_name_and_version_from_info_directory(self._dist)[1] or self._dist.version ) return parse_version(version) except TypeError: raise BadMetadata(self._dist, reason="invalid metadata entry `version`") @property def raw_version(self) -> str: return self._dist.version def is_file(self, path: InfoPath) -> bool: return self._dist.read_text(str(path)) is not None def iter_distutils_script_names(self) -> Iterator[str]: # A distutils installation is always "flat" (not in e.g. egg form), so # if this distribution's info location is NOT a pathlib.Path (but e.g. # zipfile.Path), it can never contain any distutils scripts. if not isinstance(self._info_location, pathlib.Path): return for child in self._info_location.joinpath("scripts").iterdir(): yield child.name def read_text(self, path: InfoPath) -> str: content = self._dist.read_text(str(path)) if content is None: raise FileNotFoundError(path) return content def iter_entry_points(self) -> Iterable[BaseEntryPoint]: # importlib.metadata's EntryPoint structure satisfies BaseEntryPoint. return self._dist.entry_points def _metadata_impl(self) -> email.message.Message: # From Python 3.10+, importlib.metadata declares PackageMetadata as the # return type. This protocol is unfortunately a disaster now and misses # a ton of fields that we need, including get() and get_payload(). We # rely on the implementation that the object is actually a Message now, # until upstream can improve the protocol. (python/cpython#94952) return cast(email.message.Message, self._dist.metadata) def iter_provided_extras(self) -> Iterable[NormalizedName]: return [ canonicalize_name(extra) for extra in self.metadata.get_all("Provides-Extra", []) ] def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]: contexts: Sequence[dict[str, str]] = [{"extra": e} for e in extras] for req_string in self.metadata.get_all("Requires-Dist", []): # strip() because email.message.Message.get_all() may return a leading \n # in case a long header was wrapped. req = get_requirement(req_string.strip()) if not req.marker: yield req elif not extras and req.marker.evaluate({"extra": ""}): yield req elif any(req.marker.evaluate(context) for context in contexts): yield req
Distribution
python
python__mypy
mypy/stubgen.py
{ "start": 14854, "end": 16135 }
class ____(mypy.mixedtraverser.MixedTraverserVisitor): """Find all name references (both local and global).""" # TODO: Filter out local variable and class attribute references def __init__(self) -> None: # Short names of things defined at the top level. self.refs: set[str] = set() def visit_block(self, block: Block) -> None: if not block.is_unreachable: super().visit_block(block) def visit_name_expr(self, e: NameExpr) -> None: self.refs.add(e.name) def visit_instance(self, t: Instance) -> None: self.add_ref(t.type.name) super().visit_instance(t) def visit_unbound_type(self, t: UnboundType) -> None: if t.name: self.add_ref(t.name) def visit_tuple_type(self, t: TupleType) -> None: # Ignore fallback for item in t.items: item.accept(self) def visit_callable_type(self, t: CallableType) -> None: # Ignore fallback for arg in t.arg_types: arg.accept(self) t.ret_type.accept(self) def add_ref(self, fullname: str) -> None: self.refs.add(fullname) while "." in fullname: fullname = fullname.rsplit(".", 1)[0] self.refs.add(fullname)
ReferenceFinder
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 55188, "end": 55463 }
class ____(sgqlc.types.Enum): """Properties by which package file connections can be ordered. Enumeration Choices: * `CREATED_AT`: Order package files by creation time """ __schema__ = github_schema __choices__ = ("CREATED_AT",)
PackageFileOrderField
python
getsentry__sentry
tests/sentry_plugins/github/endpoints/test_pull_request_event.py
{ "start": 549, "end": 5332 }
class ____(APITestCase): def test_opened(self) -> None: project = self.project # force creation user = self.create_user(email="alberto@sentry.io") with assume_test_silo_mode(SiloMode.CONTROL): UserSocialAuth.objects.create(provider="github", user=user, uid=6752317) self.create_member(organization=project.organization, user=user, role="member") url = f"/plugins/github/organizations/{project.organization.id}/webhook/" secret = "b3002c3e321d4b7880360d397db2ccfd" OrganizationOption.objects.set_value( organization=project.organization, key="github:webhook_secret", value=secret ) repo = Repository.objects.create( organization_id=project.organization.id, external_id="35129377", provider="github_apps", name="baxterthehacker/public-repo", ) response = self.client.post( path=url, data=PULL_REQUEST_OPENED_EVENT_EXAMPLE, content_type="application/json", HTTP_X_GITHUB_EVENT="pull_request", HTTP_X_HUB_SIGNATURE="sha1=aa5b11bc52b9fac082cb59f9ee8667cb222c3aff", HTTP_X_GITHUB_DELIVERY=str(uuid4()), ) assert response.status_code == 204 prs = PullRequest.objects.filter( repository_id=repo.id, organization_id=project.organization.id ) assert len(prs) == 1 pr = prs[0] assert pr.key == "1" assert pr.message == "This is a pretty simple change that we need to pull into master." assert pr.title == "Update the README with new information" assert pr.author is not None assert pr.author.name == "baxterthehacker" assert pr.author.email == "alberto@sentry.io" def test_edited(self) -> None: project = self.project # force creation url = f"/plugins/github/organizations/{project.organization.id}/webhook/" secret = "b3002c3e321d4b7880360d397db2ccfd" OrganizationOption.objects.set_value( organization=project.organization, key="github:webhook_secret", value=secret ) repo = Repository.objects.create( organization_id=project.organization.id, external_id="35129377", provider="github_apps", name="baxterthehacker/public-repo", ) pr = PullRequest.objects.create( key="1", repository_id=repo.id, organization_id=project.organization.id ) response = self.client.post( path=url, data=PULL_REQUEST_EDITED_EVENT_EXAMPLE, content_type="application/json", HTTP_X_GITHUB_EVENT="pull_request", HTTP_X_HUB_SIGNATURE="sha1=b50a13afd33b514e8e62e603827ea62530f0690e", HTTP_X_GITHUB_DELIVERY=str(uuid4()), ) assert response.status_code == 204 pr = PullRequest.objects.get(id=pr.id) assert pr.key == "1" assert pr.message == "new edited body" assert pr.title == "new edited title" assert pr.author is not None assert pr.author.name == "baxterthehacker" assert pr.author.email == "baxterthehacker@localhost" def test_closed(self) -> None: project = self.project # force creation url = f"/plugins/github/organizations/{project.organization.id}/webhook/" secret = "b3002c3e321d4b7880360d397db2ccfd" OrganizationOption.objects.set_value( organization=project.organization, key="github:webhook_secret", value=secret ) repo = Repository.objects.create( organization_id=project.organization.id, external_id="35129377", provider="github_apps", name="baxterthehacker/public-repo", ) response = self.client.post( path=url, data=PULL_REQUEST_CLOSED_EVENT_EXAMPLE, content_type="application/json", HTTP_X_GITHUB_EVENT="pull_request", HTTP_X_HUB_SIGNATURE="sha1=dff1c803cf1e48c1b9aefe4a17952ea132758806", HTTP_X_GITHUB_DELIVERY=str(uuid4()), ) assert response.status_code == 204 prs = PullRequest.objects.filter( repository_id=repo.id, organization_id=project.organization.id ) assert len(prs) == 1 pr = prs[0] assert pr.key == "1" assert pr.message == "new closed body" assert pr.title == "new closed title" assert pr.author is not None assert pr.author.name == "baxterthehacker" assert pr.author.email == "baxterthehacker@localhost" assert pr.merge_commit_sha == "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c"
PullRequestEventWebhook
python
celery__celery
t/unit/utils/test_collections.py
{ "start": 11755, "end": 12898 }
class ____: def test_append_limited(self): b = BufferMap(10) for i in range(20): b.put(i, i) self.assert_size_and_first(b, 10, 10) def assert_size_and_first(self, buf, size, expected_first_item): assert buf.total == size assert buf._LRUpop() == expected_first_item def test_append_unlimited(self): b = BufferMap(None) for i in range(20): b.put(i, i) self.assert_size_and_first(b, 20, 0) def test_extend_limited(self): b = BufferMap(10) b.extend(1, list(range(20))) self.assert_size_and_first(b, 10, 10) def test_extend_unlimited(self): b = BufferMap(None) b.extend(1, list(range(20))) self.assert_size_and_first(b, 20, 0) def test_pop_empty_with_default(self): b = BufferMap(10) sentinel = object() assert b.take(1, sentinel) is sentinel def test_pop_empty_no_default(self): b = BufferMap(10) with pytest.raises(b.Empty): b.take(1) def test_repr(self): assert repr(Messagebuffer(10, [1, 2, 3]))
test_BufferMap
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 99547, "end": 101773 }
class ____(AliasedReturnsRows): """Represent a subquery of a SELECT. A :class:`.Subquery` is created by invoking the :meth:`_expression.SelectBase.subquery` method, or for convenience the :meth:`_expression.SelectBase.alias` method, on any :class:`_expression.SelectBase` subclass which includes :class:`_expression.Select`, :class:`_expression.CompoundSelect`, and :class:`_expression.TextualSelect`. As rendered in a FROM clause, it represents the body of the SELECT statement inside of parenthesis, followed by the usual "AS <somename>" that defines all "alias" objects. The :class:`.Subquery` object is very similar to the :class:`_expression.Alias` object and can be used in an equivalent way. The difference between :class:`_expression.Alias` and :class:`.Subquery` is that :class:`_expression.Alias` always contains a :class:`_expression.FromClause` object whereas :class:`.Subquery` always contains a :class:`_expression.SelectBase` object. .. versionadded:: 1.4 The :class:`.Subquery` class was added which now serves the purpose of providing an aliased version of a SELECT statement. """ __visit_name__ = "subquery" _is_subquery = True inherit_cache = True element: SelectBase @classmethod def _factory( cls, selectable: SelectBase, name: Optional[str] = None ) -> Subquery: """Return a :class:`.Subquery` object.""" return coercions.expect( roles.SelectStatementRole, selectable ).subquery(name=name) @util.deprecated( "1.4", "The :meth:`.Subquery.as_scalar` method, which was previously " "``Alias.as_scalar()`` prior to version 1.4, is deprecated and " "will be removed in a future release; Please use the " ":meth:`_expression.Select.scalar_subquery` method of the " ":func:`_expression.select` " "construct before constructing a subquery object, or with the ORM " "use the :meth:`_query.Query.scalar_subquery` method.", ) def as_scalar(self) -> ScalarSelect[Any]: return self.element.set_label_style(LABEL_STYLE_NONE).scalar_subquery()
Subquery
python
facelessuser__pymdown-extensions
tests/test_extensions/test_tabbed.py
{ "start": 17905, "end": 20549 }
class ____(util.MdCase): """Combine header slug with content tab.""" extension = ['pymdownx.tabbed', 'toc', 'pymdownx.details'] extension_configs = { 'pymdownx.tabbed': { 'slugify': slugify(case='lower'), 'combine_header_slug': True } } def test_combine_header_slug(self): """Test that slugs are a combination of the header slug and the tab title.""" md = R""" ### Here is some text === "First Tab" content ### Another header ??? "title" === "Second Tab" content """ self.check_markdown( md, ''' <h3 id="here-is-some-text">Here is some text</h3> <div class="tabbed-set" data-tabs="1:1"><input checked="checked" id="here-is-some-text-first-tab" name="__tabbed_1" type="radio" /><label for="here-is-some-text-first-tab">First Tab</label><div class="tabbed-content"> <p>content</p> </div> </div> <h3 id="another-header">Another header</h3> <details> <summary>title</summary> <div class="tabbed-set" data-tabs="2:1"><input checked="checked" id="another-header-second-tab" name="__tabbed_2" type="radio" /><label for="another-header-second-tab">Second Tab</label><div class="tabbed-content"> <p>content</p> </div> </div> </details> ''', # noqa: E501 True ) def test_no_header(self): """Test when there is no header.""" md = R""" === "A Tab" content """ self.check_markdown( md, ''' <div class="tabbed-set" data-tabs="1:1"><input checked="checked" id="a-tab" name="__tabbed_1" type="radio" /><label for="a-tab">A Tab</label><div class="tabbed-content"> <p>content</p> </div> </div> ''', # noqa: E501 True ) def test_header_after(self): """Test when header comes after.""" md = R""" === "A Tab" content # Header """ self.check_markdown( md, ''' <div class="tabbed-set" data-tabs="1:1"><input checked="checked" id="a-tab" name="__tabbed_1" type="radio" /><label for="a-tab">A Tab</label><div class="tabbed-content"> <p>content</p> </div> </div> <h1 id="header">Header</h1> ''', # noqa: E501 True )
TestTabSlugsCombineHeader
python
getsentry__sentry
src/sentry/dynamic_sampling/types.py
{ "start": 343, "end": 503 }
class ____(Enum): """The type of data being measured for dynamic sampling rebalancing.""" SPANS = "spans" TRANSACTIONS = "transactions"
SamplingMeasure
python
pypa__setuptools
setuptools/_vendor/importlib_metadata/__init__.py
{ "start": 1352, "end": 2927 }
class ____: """ A simple entry point config parser for performance >>> for item in Sectioned.read(Sectioned._sample): ... print(item) Pair(name='sec1', value='# comments ignored') Pair(name='sec1', value='a = 1') Pair(name='sec1', value='b = 2') Pair(name='sec2', value='a = 2') >>> res = Sectioned.section_pairs(Sectioned._sample) >>> item = next(res) >>> item.name 'sec1' >>> item.value Pair(name='a', value='1') >>> item = next(res) >>> item.value Pair(name='b', value='2') >>> item = next(res) >>> item.name 'sec2' >>> item.value Pair(name='a', value='2') >>> list(res) [] """ _sample = textwrap.dedent( """ [sec1] # comments ignored a = 1 b = 2 [sec2] a = 2 """ ).lstrip() @classmethod def section_pairs(cls, text): return ( section._replace(value=Pair.parse(section.value)) for section in cls.read(text, filter_=cls.valid) if section.name is not None ) @staticmethod def read(text, filter_=None): lines = filter(filter_, map(str.strip, text.splitlines())) name = None for value in lines: section_match = value.startswith('[') and value.endswith(']') if section_match: name = value.strip('[]') continue yield Pair(name, value) @staticmethod def valid(line: str): return line and not line.startswith('#')
Sectioned
python
ansible__ansible
test/units/module_utils/datatag/test_datatag.py
{ "start": 11028, "end": 11659 }
class ____: def pytest_generate_tests(self, metafunc: pytest.Metafunc): for node, mark in metafunc.definition.iter_markers_with_node("autoparam"): attrname = mark.args[0] test_arg_names = set(inspect.signature(metafunc.function).parameters) argnames, argvalues, id_func = ParamDesc.get_test_param_values(metafunc.cls, attrname, test_arg_names) if argnames: metafunc.parametrize(argnames, argvalues, ids=id_func) def __init_subclass__(cls, **kwargs): cls.post_init() @classmethod def post_init(cls) -> None: ...
AutoParamSupport
python
django__django
tests/file_storage/tests.py
{ "start": 1346, "end": 2246 }
class ____(unittest.TestCase): def test_deconstruction(self): path, args, kwargs = temp_storage.deconstruct() self.assertEqual(path, "django.core.files.storage.FileSystemStorage") self.assertEqual(args, ()) self.assertEqual(kwargs, {"location": temp_storage_location}) kwargs_orig = { "location": temp_storage_location, "base_url": "http://myfiles.example.com/", } storage = FileSystemStorage(**kwargs_orig) path, args, kwargs = storage.deconstruct() self.assertEqual(kwargs, kwargs_orig) def test_lazy_base_url_init(self): """ FileSystemStorage.__init__() shouldn't evaluate base_url. """ storage = FileSystemStorage(base_url=reverse_lazy("app:url")) with self.assertRaises(NoReverseMatch): storage.url(storage.base_url)
FileSystemStorageTests
python
huggingface__transformers
src/transformers/models/wavlm/modeling_wavlm.py
{ "start": 56900, "end": 61140 }
class ____(WavLMPreTrainedModel): def __init__(self, config): super().__init__(config) if hasattr(config, "add_adapter") and config.add_adapter: raise ValueError( "Audio frame classification does not support the use of WavLM adapters (config.add_adapter=True)" ) self.wavlm = WavLMModel(config) num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings if config.use_weighted_layer_sum: self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers) self.classifier = nn.Linear(config.hidden_size, config.num_labels) self.num_labels = config.num_labels self.post_init() def freeze_feature_encoder(self): """ Calling this function will disable the gradient computation for the feature encoder so that its parameter will not be updated during training. """ self.wavlm.feature_extractor._freeze_parameters() def freeze_base_model(self): """ Calling this function will disable the gradient computation for the base model so that its parameters will not be updated during training. Only the classification head will be updated. """ for param in self.wavlm.parameters(): param.requires_grad = False @auto_docstring def forward( self, input_values: Optional[torch.Tensor], attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, TokenClassifierOutput]: r""" input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or the soundfile library (`pip install soundfile`). To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion into a tensor of type `torch.FloatTensor`. See [`WavLMProcessor.__call__`] for details. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states outputs = self.wavlm( input_values, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) if self.config.use_weighted_layer_sum: hidden_states = outputs[_HIDDEN_STATES_START_POSITION] hidden_states = torch.stack(hidden_states, dim=1) norm_weights = nn.functional.softmax(self.layer_weights, dim=-1) hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1) else: hidden_states = outputs[0] logits = self.classifier(hidden_states) loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1)) if not return_dict: output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:] return output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
WavLMForAudioFrameClassification
python
bokeh__bokeh
src/bokeh/models/glyphs.py
{ "start": 19186, "end": 21243 }
class ____(Glyph, LineGlyph, FillGlyph, HatchGlyph): ''' Render horizontal tiles on a regular hexagonal grid. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) __example__ = "examples/reference/models/HexTile.py" _args = ('q', 'r') size = Float(1.0, help=""" The radius (in |data units|) of the hex tiling. The radius is always measured along the cartesian y-axis for "pointy_top" orientation, and along the cartesian x-axis for "flat_top" orientation. If the aspect ratio of the underlying cartesian system is not 1-1, then the tiles may be "squished" in one direction. To ensure that the tiles are always regular hexagons, consider setting the ``match_aspect`` property of the plot to True. """) aspect_scale = Float(default=1.0, help=""" Match a plot's aspect ratio scaling. Use this parameter to match the aspect ratio scaling of a plot when using :class:`~bokeh.models.Plot.aspect_scale` with a value other than ``1.0``. """) r = NumberSpec(default=field("r"), help=""" The "row" axial coordinates of the tile centers. """) q = NumberSpec(default=field("q"), help=""" The "column" axial coordinates of the tile centers. """) scale = NumberSpec(1.0, help=""" A scale factor for individual tiles. """) orientation = Enum(HexTileOrientation, default="pointytop", help=""" The orientation of the hex tiles. Use ``"pointytop"`` to orient the tile so that a pointed corner is at the top. Use ``"flattop"`` to orient the tile so that a flat side is at the top. """) line_props = Include(LineProps, help=""" The {prop} values for the hex tiles. """) line_color = Override(default=None) fill_props = Include(FillProps, help=""" The {prop} values for the hex tiles. """) hatch_props = Include(HatchProps, help=""" The {prop} values for the hex tiles. """) @abstract
HexTile
python
tensorflow__tensorflow
tensorflow/python/keras/callbacks.py
{ "start": 104246, "end": 106644 }
class ____(Callback): """Callback that streams epoch results to a CSV file. Supports all values that can be represented as a string, including 1D iterables such as `np.ndarray`. Example: ```python csv_logger = CSVLogger('training.log') model.fit(X_train, Y_train, callbacks=[csv_logger]) ``` Args: filename: Filename of the CSV file, e.g. `'run/log.csv'`. separator: String used to separate elements in the CSV file. append: Boolean. True: append if file exists (useful for continuing training). False: overwrite existing file. """ def __init__(self, filename, separator=',', append=False): self.sep = separator self.filename = path_to_string(filename) self.append = append self.writer = None self.keys = None self.append_header = True super(CSVLogger, self).__init__() def on_train_begin(self, logs=None): if self.append: if file_io.file_exists_v2(self.filename): with gfile.GFile(self.filename, 'r') as f: self.append_header = not bool(len(f.readline())) mode = 'a' else: mode = 'w' self.csv_file = gfile.GFile(self.filename, mode) def on_epoch_end(self, epoch, logs=None): logs = logs or {} def handle_value(k): is_zero_dim_ndarray = isinstance(k, np.ndarray) and k.ndim == 0 if isinstance(k, str): return k elif isinstance(k, collections.abc.Iterable) and not is_zero_dim_ndarray: return '"[%s]"' % (', '.join(map(str, k))) else: return k if self.keys is None: self.keys = sorted(logs.keys()) if self.model.stop_training: # We set NA so that csv parsers do not fail for this last epoch. logs = dict((k, logs[k]) if k in logs else (k, 'NA') for k in self.keys) if not self.writer: class CustomDialect(csv.excel): delimiter = self.sep fieldnames = ['epoch'] + self.keys self.writer = csv.DictWriter( self.csv_file, fieldnames=fieldnames, dialect=CustomDialect) if self.append_header: self.writer.writeheader() row_dict = collections.OrderedDict({'epoch': epoch}) row_dict.update((key, handle_value(logs[key])) for key in self.keys) self.writer.writerow(row_dict) self.csv_file.flush() def on_train_end(self, logs=None): self.csv_file.close() self.writer = None
CSVLogger
python
scrapy__scrapy
tests/mockserver/http_resources.py
{ "start": 6764, "end": 7092 }
class ____(resource.Resource): def render(self, request): from twisted.internet import reactor def response(): request.write(b"chunked ") request.write(b"content\n") request.finish() reactor.callLater(0, response) return server.NOT_DONE_YET
ChunkedResource
python
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster/subschema/daemon.py
{ "start": 1175, "end": 1347 }
class ____(BaseModel): queuedRunCoordinator: Optional[QueuedRunCoordinatorConfig] = None customRunCoordinator: Optional[ConfigurableClass] = None
RunCoordinatorConfig
python
google__jax
tests/ffi_test.py
{ "start": 1292, "end": 13990 }
class ____(jtu.JaxTestCase): def find_custom_call_in_module(self, module): for func in module.body.operations: for block in func.body.blocks: for op in block.operations: if op.OPERATION_NAME == "stablehlo.custom_call": return op self.fail("No custom_call found in the lowered IR") def test_headers_exist(self): base_dir = os.path.join(jax.ffi.include_dir(), "xla", "ffi", "api") for header in ["c_api.h", "api.h", "ffi.h"]: self.assertTrue(os.path.exists(os.path.join(base_dir, header))) @parameterized.parameters([ (tuple(range(3)), tuple(range(3))), (None, tuple(reversed(range(3)))), (Layout(tuple(range(3))), tuple(reversed(range(3)))), ]) def test_lowering_layouts(self, layout_spec, expected_layout): # Regression test to ensure that the lowering rule properly captures # layouts. def lowering_rule(ctx, x): return jax.ffi.ffi_lowering("test_ffi", operand_layouts=[layout_spec], result_layouts=[layout_spec])(ctx, x) prim = core.Primitive("test_ffi") prim.def_impl(lambda x: x) prim.def_abstract_eval(lambda x: x) mlir.register_lowering(prim, lowering_rule) x = jnp.ones((3,) * len(expected_layout)) lowered = jax.jit(prim.bind).lower(x) module = lowered.compiler_ir("stablehlo") op = self.find_custom_call_in_module(module) self.assertIn("operand_layouts", op.attributes) self.assertIn("result_layouts", op.attributes) text = lowered.as_text() expected = ", ".join(map(str, expected_layout)) pattern = rf"operand_layouts = \[dense<\[{expected}\]>" self.assertRegex(text, pattern) pattern = rf"result_layouts = \[dense<\[{expected}\]>" self.assertRegex(text, pattern) # Concise helpers to every test instance below in one line. _arr = lambda value, dtype=None: np.array(value, dtype=dtype) _ftens1 = lambda et: f"dense<1.000000e+00> : tensor<{et}>" _itens1 = lambda et: f"dense<1> : tensor<{et}>" @parameterized.parameters( (_arr(1, dtypes.int2), _itens1("i2")), (_arr(1, dtypes.int4), _itens1("i4")), (_arr(1, dtypes.uint2), _itens1("ui2")), (_arr(1, dtypes.uint4), _itens1("ui4")), (_arr(1, np.int16), _itens1("i16")), (_arr(1, np.int32), _itens1("i32")), (_arr(1, np.int64), _itens1("i64")), (_arr(1, np.int8), _itens1("i8")), (_arr(1, np.uint16), _itens1("ui16")), (_arr(1, np.uint32), _itens1("ui32")), (_arr(1, np.uint64), _itens1("ui64")), (_arr(1, np.uint8), _itens1("ui8")), (_arr(1.0, dtypes.bfloat16), _ftens1("bf16")), (_arr(1.0, dtypes.float4_e2m1fn), _ftens1("f4E2M1FN")), (_arr(1.0, dtypes.float8_e3m4), _ftens1("f8E3M4")), (_arr(1.0, dtypes.float8_e4m3), _ftens1("f8E4M3")), (_arr(1.0, dtypes.float8_e4m3b11fnuz), _ftens1("f8E4M3B11FNUZ")), (_arr(1.0, dtypes.float8_e4m3fn), _ftens1("f8E4M3FN")), (_arr(1.0, dtypes.float8_e4m3fnuz), _ftens1("f8E4M3FNUZ")), (_arr(1.0, dtypes.float8_e5m2), _ftens1("f8E5M2")), (_arr(1.0, dtypes.float8_e5m2fnuz), _ftens1("f8E5M2FNUZ")), (_arr(1.0, dtypes.float8_e8m0fnu), _ftens1("f8E8M0FNU")), (_arr(1.0, np.bool), "dense<true> : tensor<i1>"), (_arr(1.0, np.float16), _ftens1("f16")), (_arr(1.0, np.float32), _ftens1("f32")), (_arr(1.0, np.float64), _ftens1("f64")), (dtypes.bfloat16(1.0), "1.000000e+00 : bf16"), (np.bool(False), "false"), (np.bool(True), "true"), (np.float16(1.0), "1.000000e+00 : f16"), (np.float32(1.0), "1.000000e+00 : f32"), (np.float64(1.0), "1.000000e+00 : f64"), (np.int16(1), "1 : i16"), (np.int32(1), "1 : i32"), (np.int64(1), "1 : i64"), (np.int8(1), "1 : i8"), (np.uint16(1), "1 : ui16"), (np.uint32(1), "1 : ui32"), (np.uint64(1), "1 : ui64"), (np.uint8(1), "1 : ui8"), (np.zeros((), dtype=dtypes.float0), "dense<false> : tensor<i1>"), ("param", '"param"'), ) def test_params(self, param, expected_str): def fun(x): return jax.ffi.ffi_call("test_ffi", x)(x, param=param) # Here we inspect the lowered IR to test that the parameter has been # serialized with the appropriate type. module = jax.jit(fun).lower(0.5).compiler_ir("stablehlo") op = self.find_custom_call_in_module(module) conf = op.attributes["mhlo.backend_config"] self.assertIsInstance(conf, mlir.ir.DictAttr) self.assertIn("param", conf) self.assertEqual(str(conf["param"]), expected_str) def test_token(self): def fun(): token = lax.create_token() return jax.ffi.ffi_call("test_ffi", core.abstract_token)(token) # Ensure that token inputs and outputs are translated to the correct type module = jax.jit(fun).lower().compiler_ir("stablehlo") op = self.find_custom_call_in_module(module) self.assertTrue(hlo.TokenType.isinstance(op.operands[0].type)) self.assertTrue(hlo.TokenType.isinstance(op.results[0].type)) def test_effects_hlo(self): # The target name must exist on the current platform, but we don't actually # need to call it with the correct syntax, because we're only checking the # compiled HLO. if jtu.test_device_matches(["cpu"]): target_name = "lapack_sgetrf_ffi" elif jtu.test_device_matches(["rocm"]): target_name = "hipsolver_getrf_ffi" elif jtu.test_device_matches(["cuda", "gpu"]): target_name = "cusolver_getrf_ffi" else: raise unittest.SkipTest("Unsupported device") def fun(): jax.ffi.ffi_call(target_name, (), has_side_effect=True)() hlo = jax.jit(fun).lower() self.assertIn(target_name, hlo.as_text()) self.assertIn("has_side_effect = true", hlo.as_text()) self.assertIn(target_name, hlo.compile().as_text()) def test_jvp_error(self): def fun(x): return jax.ffi.ffi_call("test_ffi", x)(x, non_hashable_arg={"a": 1}) with self.assertRaisesRegex( ValueError, "The FFI call to `.+` cannot be differentiated."): jax.jvp(fun, (0.5,), (0.5,)) def test_non_hashable_attributes(self): def fun(x): return jax.ffi.ffi_call("test_ffi", x)(x, non_hashable_arg={"a": 1}) self.assertIn("FrozenDict", str(jax.make_jaxpr(fun)(jnp.ones(5)))) hlo = jax.jit(fun).lower(jnp.ones(5)).as_text() self.assertIn("non_hashable_arg = {a = 1", hlo) # If non-hashable arguments aren't handled properly, this will raise a # TypeError. We make sure it doesn't. with self.assertRaises(Exception) as manager: fun(jnp.ones(5)) self.assertNotIsInstance(manager.exception, TypeError) def fun(x): return jax.ffi.ffi_call("test_ffi", x)(x, non_hashable_arg=np.arange(3)) self.assertIn("HashableArray", str(jax.make_jaxpr(fun)(jnp.ones(5)))) hlo = jax.jit(fun).lower(jnp.ones(5)).as_text() self.assertIn("non_hashable_arg = dense<[0, 1, 2]> : tensor<3xi64>", hlo) with self.assertRaises(Exception) as manager: fun(jnp.ones(5)) self.assertNotIsInstance(manager.exception, TypeError) @jtu.sample_product(shape=[(6, 5), (4, 5, 6)]) @jtu.run_on_devices("gpu", "cpu") def test_ffi_call(self, shape): x = self.rng().randn(*shape).astype(np.float32) expected = lax_linalg_internal.geqrf(x) actual = ffi_call_geqrf(x) for a, b in zip(actual, expected): self.assertArraysEqual(a, b) @jtu.sample_product( shape=[(6, 5), (4, 5, 6)], vmap_method=["expand_dims", "broadcast_all", "sequential", "sequential_unrolled"], ) @jtu.run_on_devices("gpu", "cpu") def test_ffi_call_batching(self, shape, vmap_method): shape = (10,) + shape x = self.rng().randn(*shape).astype(np.float32) expected = lax_linalg_internal.geqrf(x) actual = jax.vmap(partial(ffi_call_geqrf, vmap_method=vmap_method))(x) for a, b in zip(actual, expected): if vmap_method.startswith("sequential") and len(shape) == 3: # On GPU, the batched FFI call to geqrf uses an algorithm with # different numerics than the unbatched version (which is used when # vmap_method="sequential"). Therefore, we need to include floating # point tolerance for this check. self.assertArraysAllClose(a, b) else: self.assertArraysEqual(a, b) def test_input_output_aliases(self): def fun(x): return jax.ffi.ffi_call("test", x, input_output_aliases={0: 0})(x) hlo = jax.jit(fun).lower(jnp.ones(5)).as_text() self.assertRegex(hlo, r"output_operand_aliases = \[.*operand_index = 0.*\]") def test_invalid_input_output_aliases(self): def fun(x): return jax.ffi.ffi_call("test", x, input_output_aliases={1: 0})(x) with self.assertRaisesRegex(ValueError, "with input index"): jax.jit(fun).lower(jnp.ones(5)).as_text() def fun(x): return jax.ffi.ffi_call("test", x, input_output_aliases={0: 1})(x) with self.assertRaisesRegex(ValueError, "with output index"): jax.jit(fun).lower(jnp.ones(5)).as_text() def fun(x): return jax.ffi.ffi_call("test", jax.ShapeDtypeStruct(x.shape, np.int32), input_output_aliases={0: 0})(x) with self.assertRaisesRegex(ValueError, "referring to an input with abstract value"): jax.jit(fun).lower(jnp.ones(5)).as_text() def fun(x): return jax.ffi.ffi_call("test", jax.ShapeDtypeStruct(x.shape + x.shape, x.dtype), input_output_aliases={0: 0})(x) with self.assertRaisesRegex(ValueError, "referring to an input with abstract value"): jax.jit(fun).lower(jnp.ones(5)).as_text() def test_legacy_backend_config(self): def fun(x): return jax.ffi.ffi_call("test", x, custom_call_api_version=2, legacy_backend_config="12345")(x) hlo = jax.jit(fun).lower(jnp.ones(5)).as_text() self.assertRegex(hlo, 'backend_config = "12345"') def test_invalid_backend_config(self): def fun(x): return jax.ffi.ffi_call("test", x, legacy_backend_config="12345")(x) with self.assertRaisesRegex(ValueError, "The use of the legacy_backend_config"): jax.jit(fun).lower(jnp.ones(5)).as_text() def fun(x): return jax.ffi.ffi_call("test", x, custom_call_api_version=2)(x, attribute=1) with self.assertRaisesRegex(ValueError, "The use of ffi_call attributes requires"): jax.jit(fun).lower(jnp.ones(5)).as_text() def test_allow_x64(self): if not config.enable_x64.value: self.skipTest("Requires enable_x64=False") def fun(): return jax.ffi.ffi_call("test", jax.ShapeDtypeStruct((), np.int64))() self.assertIn("tensor<i64>", jax.jit(fun).lower().as_text()) def test_invalid_result_type(self): with self.assertRaisesRegex( TypeError, "Cannot interpret value of type.*"): jax.ffi.ffi_call("test", None)() with self.assertRaisesRegex( TypeError, "Cannot interpret value of type.*"): jax.ffi.ffi_call("test", (jax.ShapeDtypeStruct((), np.float32), ()))() @jtu.run_on_devices("gpu", "cpu") def test_shard_map(self): mesh = jtu.create_mesh((len(jax.devices()),), ("i",)) x = self.rng().randn(8, 4, 5).astype(np.float32) @partial(shard_map, mesh=mesh, in_specs=P("i"), out_specs=P("i")) def f(x): return ffi_call_geqrf(x) f(x) # eager mode doesn't crash jax.jit(f)(x) # neither does JIT self.assertNotIn("all-gather", jax.jit(f).lower(x).compile().as_text()) def test_extended_dtype_lowering(self): def f(x): return jax.ffi.ffi_call("edtype", (), has_side_effect=True)(x) jax.jit(f).lower(jax.random.key(0)) # doesn't crash def ffi_call_geqrf(x, **kwargs): if jtu.test_device_matches(["cpu"]): lapack._lapack.initialize() assert x.dtype == np.float32 ndim = x.ndim x_major_to_minor = tuple(range(ndim - 2)) + (ndim - 1, ndim - 2) output_types = [ x, jax.ShapeDtypeStruct(x.shape[:-2] + (min(*x.shape[-2:]),), x.dtype)] def call(platform, x): target_name = dict( cpu="lapack_sgeqrf_ffi", rocm="hipsolver_geqrf_ffi", cuda="cusolver_geqrf_ffi", )[platform] return jax.ffi.ffi_call( target_name, output_types, input_output_aliases={0: 0}, input_layouts=[x_major_to_minor], output_layouts=[x_major_to_minor, None], **kwargs)(x) return lax.platform_dependent( x, cpu=partial(call, "cpu"), rocm=partial(call, "rocm"), cuda=partial(call, "cuda"))
FfiTest
python
fastai__fastai
fastai/layers.py
{ "start": 4270, "end": 4644 }
class ____(Module): "Layer that concats `AdaptiveAvgPool1d` and `AdaptiveMaxPool1d`" def __init__(self, size=None): self.size = size or 1 self.ap = nn.AdaptiveAvgPool1d(self.size) self.mp = nn.AdaptiveMaxPool1d(self.size) def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1) # %% ../nbs/01_layers.ipynb 28
AdaptiveConcatPool1d
python
getsentry__sentry
src/sentry/auth/email.py
{ "start": 388, "end": 953 }
class ____(Exception): def __init__(self, email: str, users: Collection[User]) -> None: super().__init__(f"Resolved {email!r} to {[user.id for user in users]}") self.email = email self.users = tuple(users) def resolve_email_to_user(email: str, organization: Organization | None = None) -> User | None: candidates = tuple(UserEmail.objects.filter(email__iexact=email, user__is_active=True)) if not candidates: return None return _EmailResolver(email, organization).resolve(candidates) @dataclass
AmbiguousUserFromEmail
python
facebookresearch__faiss
faiss/gpu/test/test_cuvs.py
{ "start": 383, "end": 2766 }
class ____(unittest.TestCase): def test_large_k_search(self): k = 10_000 ds = SyntheticDataset(32, 100_000, 100_000, 1000) res = faiss.StandardGpuResources() config = faiss.GpuIndexFlatConfig() config.use_cuvs = True index_gpu = faiss.GpuIndexFlatL2(res, ds.d, config) index_gpu.add(ds.get_database()) # Try larger than 2048 _, I = index_gpu.search(ds.get_queries(), k) np.testing.assert_equal(I.shape, (ds.nq, k)) def test_bfKnn(self): ds = SyntheticDataset(32, 0, 4321, 1234) Dref, Iref = faiss.knn(ds.get_queries(), ds.get_database(), 12) res = faiss.StandardGpuResources() # Faiss internal implementation Dnew, Inew = faiss.knn_gpu( res, ds.get_queries(), ds.get_database(), 12, use_cuvs=False) np.testing.assert_allclose(Dref, Dnew, atol=1e-4) np.testing.assert_array_equal(Iref, Inew) # cuVS version Dnew, Inew = faiss.knn_gpu( res, ds.get_queries(), ds.get_database(), 12, use_cuvs=True) np.testing.assert_allclose(Dref, Dnew, atol=1e-4) np.testing.assert_array_equal(Iref, Inew) def test_IndexFlat(self): ds = SyntheticDataset(32, 0, 4000, 1234) # add only first half of database xb = ds.get_database() index = faiss.IndexFlatL2(ds.d) index.add(xb[:2000]) Dref, Iref = index.search(ds.get_queries(), 13) res = faiss.StandardGpuResources() co = faiss.GpuClonerOptions() co.use_cuvs = True index_gpu = faiss.index_cpu_to_gpu(res, 0, index, co) Dnew, Inew = index_gpu.search(ds.get_queries(), 13) np.testing.assert_allclose(Dref, Dnew, atol=1e-5) np.testing.assert_array_equal(Iref, Inew) # add rest of database index.add(xb[2000:]) Dref, Iref = index.search(ds.get_queries(), 13) index_gpu.add(xb[2000:]) Dnew, Inew = index_gpu.search(ds.get_queries(), 13) np.testing.assert_allclose(Dref, Dnew, atol=1e-4) np.testing.assert_array_equal(Iref, Inew) # copy back to CPU index2 = faiss.index_gpu_to_cpu(index_gpu) Dnew, Inew = index2.search(ds.get_queries(), 13) np.testing.assert_allclose(Dref, Dnew, atol=1e-4) np.testing.assert_array_equal(Iref, Inew)
TestBfKnn
python
RaRe-Technologies__gensim
gensim/test/test_similarity_metrics.py
{ "start": 497, "end": 2176 }
class ____(unittest.TestCase): def test_None(self): # test None result = matutils.isbow(None) expected = False self.assertEqual(expected, result) def test_bow(self): # test list words # one bag of words potentialbow = [(0, 0.4)] result = matutils.isbow(potentialbow) expected = True self.assertEqual(expected, result) # multiple bags potentialbow = [(0, 4.), (1, 2.), (2, 5.), (3, 8.)] result = matutils.isbow(potentialbow) expected = True self.assertEqual(expected, result) # checking empty input potentialbow = [] result = matutils.isbow(potentialbow) expected = True self.assertEqual(expected, result) # checking corpus; should return false potentialbow = [[(2, 1), (3, 1), (4, 1), (5, 1), (1, 1), (7, 1)]] result = matutils.isbow(potentialbow) expected = False self.assertEqual(expected, result) # not a bag of words, should return false potentialbow = [(1, 3, 6)] result = matutils.isbow(potentialbow) expected = False self.assertEqual(expected, result) # checking sparse matrix format bag of words potentialbow = csr_matrix([[1, 0.4], [0, 0.3], [2, 0.1]]) result = matutils.isbow(potentialbow) expected = True self.assertEqual(expected, result) # checking np array format bag of words potentialbow = np.array([[1, 0.4], [0, 0.2], [2, 0.2]]) result = matutils.isbow(potentialbow) expected = True self.assertEqual(expected, result)
TestIsBow
python
getsentry__sentry
tests/sentry/feedback/endpoints/test_project_user_reports.py
{ "start": 7986, "end": 18418 }
class ____(APITestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.min_ago = before_now(minutes=1).isoformat() self.hour_ago = before_now(minutes=60).isoformat() self.project = self.create_project() self.environment = self.create_environment(project=self.project) self.event = self.store_event( data={ "timestamp": self.min_ago, "environment": self.environment.name, "user": {"email": "foo@example.com"}, }, project_id=self.project.id, ) self.old_event = self.store_event( data={"timestamp": self.hour_ago, "environment": self.environment.name}, project_id=self.project.id, ) def test_simple(self) -> None: self.login_as(user=self.user) url = _make_url(self.project) response = self.client.post( url, data={ "event_id": self.event.event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 200, response.content report = UserReport.objects.get(id=response.data["id"]) assert report.project_id == self.project.id assert report.group_id == self.event.group.id assert report.email == "foo@example.com" assert report.name == "Foo Bar" assert report.comments == "It broke!" def test_with_dsn_auth(self) -> None: project_key = self.create_project_key(project=self.project) url = _make_url(self.project) response = self.client.post( url, HTTP_AUTHORIZATION=f"DSN {project_key.dsn_public}", data={ "event_id": self.event.event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 200, response.content # DSN auth shouldn't return any data assert not response.data def test_with_dsn_auth_invalid_project(self) -> None: project2 = self.create_project() project_key = self.create_project_key(project=self.project) url = _make_url(project2) response = self.client.post( url, HTTP_AUTHORIZATION=f"DSN {project_key.dsn_public}", data={ "event_id": uuid4().hex, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 401, response.content def test_already_present(self) -> None: self.login_as(user=self.user) UserReport.objects.create( group_id=self.event.group.id, project_id=self.project.id, event_id=self.event.event_id, name="foo", email="bar@example.com", comments="", ) url = _make_url(self.project) response = self.client.post( url, data={ "event_id": self.event.event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 200, response.content report = UserReport.objects.get(id=response.data["id"]) assert report.project_id == self.project.id assert report.group_id == self.event.group.id assert report.email == "foo@example.com" assert report.name == "Foo Bar" assert report.comments == "It broke!" def test_already_present_after_deadline(self) -> None: self.login_as(user=self.user) UserReport.objects.create( group_id=self.old_event.group.id, project_id=self.project.id, event_id=self.old_event.event_id, name="foo", email="bar@example.com", comments="", date_added=timezone.now() - timedelta(minutes=10), ) url = _make_url(self.project) response = self.client.post( url, data={ "event_id": self.old_event.event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 409, response.content def test_after_event_deadline(self) -> None: self.login_as(user=self.user) url = _make_url(self.project) response = self.client.post( url, data={ "event_id": self.old_event.event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 409, response.content def test_environments(self) -> None: self.login_as(user=self.user) url = _make_url(self.project) response = self.client.post( url, data={ "event_id": self.event.event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 200, response.content assert ( UserReport.objects.get(event_id=self.event.event_id).environment_id == self.environment.id ) @patch("sentry.feedback.usecases.ingest.create_feedback.produce_occurrence_to_kafka") def test_simple_shim_to_feedback(self, mock_produce_occurrence_to_kafka: MagicMock) -> None: replay_id = "b" * 32 event_with_replay = self.store_event( data={ "contexts": {"replay": {"replay_id": replay_id}}, "event_id": "a" * 32, "timestamp": self.min_ago, "environment": self.environment.name, "tags": {"foo": "bar"}, }, project_id=self.project.id, ) self.login_as(user=self.user) url = _make_url(self.project) response = self.client.post( url, data={ "event_id": event_with_replay.event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 200, response.content report = UserReport.objects.get(id=response.data["id"]) assert report.project_id == self.project.id assert report.group_id == event_with_replay.group.id assert report.email == "foo@example.com" assert report.name == "Foo Bar" assert report.comments == "It broke!" assert len(mock_produce_occurrence_to_kafka.mock_calls) == 1 mock_event_data = mock_produce_occurrence_to_kafka.call_args_list[0][1]["event_data"] assert mock_event_data["contexts"]["feedback"]["contact_email"] == "foo@example.com" assert mock_event_data["contexts"]["feedback"]["message"] == "It broke!" assert mock_event_data["contexts"]["feedback"]["name"] == "Foo Bar" assert mock_event_data["contexts"]["feedback"]["replay_id"] == replay_id assert mock_event_data["contexts"]["replay"]["replay_id"] == replay_id assert mock_event_data["environment"] == self.environment.name assert mock_event_data["tags"]["environment"] == self.environment.name assert mock_event_data["tags"]["foo"] == "bar" assert mock_event_data["tags"]["level"] == "error" assert mock_event_data["tags"]["user.email"] == "foo@example.com" assert mock_event_data["platform"] == "other" assert ( mock_event_data["contexts"]["feedback"]["associated_event_id"] == event_with_replay.event_id ) assert mock_event_data["level"] == "error" @patch("sentry.feedback.usecases.ingest.create_feedback.produce_occurrence_to_kafka") def test_simple_shim_to_feedback_no_event_should_not_call( self, mock_produce_occurrence_to_kafka ): self.login_as(user=self.user) url = _make_url(self.project) event_id = uuid4().hex response = self.client.post( url, data={ "event_id": event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 200, response.content report = UserReport.objects.get(id=response.data["id"]) assert report.project_id == self.project.id assert report.email == "foo@example.com" assert report.name == "Foo Bar" assert report.comments == "It broke!" assert len(mock_produce_occurrence_to_kafka.mock_calls) == 0 @patch("sentry.feedback.usecases.ingest.userreport.validate_user_report") def test_validation_error(self, mock_validate_user_report: MagicMock) -> None: mock_validate_user_report.return_value = (True, "data_invalid", "Data invalid") self.login_as(user=self.user) url = _make_url(self.project) response = self.client.post( url, data={ "event_id": self.event.event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 400, response.content assert UserReport.objects.count() == 0 @patch("sentry.feedback.usecases.ingest.userreport.is_in_feedback_denylist") def test_denylist(self, mock_is_in_feedback_denylist: MagicMock) -> None: mock_is_in_feedback_denylist.return_value = True self.login_as(user=self.user) url = _make_url(self.project) response = self.client.post( url, data={ "event_id": self.event.event_id, "email": "foo@example.com", "name": "Foo Bar", "comments": "It broke!", }, ) assert response.status_code == 403, response.content assert UserReport.objects.count() == 0
CreateProjectUserReportTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/io_ops/reader_ops_test.py
{ "start": 4019, "end": 9449 }
class ____(test.TestCase): def _ExpectRead(self, key, value, expected): k, v = self.evaluate([key, value]) self.assertAllEqual(expected, k) self.assertAllEqual(expected, v) @test_util.run_deprecated_v1 def testOneEpoch(self): reader = io_ops.IdentityReader("test_reader") work_completed = reader.num_work_units_completed() produced = reader.num_records_produced() queue = data_flow_ops.FIFOQueue(99, [dtypes.string], shapes=()) queued_length = queue.size() key, value = reader.read(queue) self.assertAllEqual(0, self.evaluate(work_completed)) self.assertAllEqual(0, self.evaluate(produced)) self.assertAllEqual(0, self.evaluate(queued_length)) self.evaluate(queue.enqueue_many([["A", "B", "C"]])) self.evaluate(queue.close()) self.assertAllEqual(3, self.evaluate(queued_length)) self._ExpectRead(key, value, b"A") self.assertAllEqual(1, self.evaluate(produced)) self._ExpectRead(key, value, b"B") self._ExpectRead(key, value, b"C") self.assertAllEqual(3, self.evaluate(produced)) self.assertAllEqual(0, self.evaluate(queued_length)) with self.assertRaisesOpError("is closed and has insufficient elements " "\\(requested 1, current size 0\\)"): self.evaluate([key, value]) self.assertAllEqual(3, self.evaluate(work_completed)) self.assertAllEqual(3, self.evaluate(produced)) self.assertAllEqual(0, self.evaluate(queued_length)) @test_util.run_deprecated_v1 def testMultipleEpochs(self): reader = io_ops.IdentityReader("test_reader") queue = data_flow_ops.FIFOQueue(99, [dtypes.string], shapes=()) enqueue = queue.enqueue_many([["DD", "EE"]]) key, value = reader.read(queue) self.evaluate(enqueue) self._ExpectRead(key, value, b"DD") self._ExpectRead(key, value, b"EE") self.evaluate(enqueue) self._ExpectRead(key, value, b"DD") self._ExpectRead(key, value, b"EE") self.evaluate(enqueue) self._ExpectRead(key, value, b"DD") self._ExpectRead(key, value, b"EE") self.evaluate(queue.close()) with self.assertRaisesOpError("is closed and has insufficient elements " "\\(requested 1, current size 0\\)"): self.evaluate([key, value]) @test_util.run_deprecated_v1 def testSerializeRestore(self): reader = io_ops.IdentityReader("test_reader") produced = reader.num_records_produced() queue = data_flow_ops.FIFOQueue(99, [dtypes.string], shapes=()) self.evaluate(queue.enqueue_many([["X", "Y", "Z"]])) key, value = reader.read(queue) self._ExpectRead(key, value, b"X") self.assertAllEqual(1, self.evaluate(produced)) state = self.evaluate(reader.serialize_state()) self._ExpectRead(key, value, b"Y") self._ExpectRead(key, value, b"Z") self.assertAllEqual(3, self.evaluate(produced)) self.evaluate(queue.enqueue_many([["Y", "Z"]])) self.evaluate(queue.close()) self.evaluate(reader.restore_state(state)) self.assertAllEqual(1, self.evaluate(produced)) self._ExpectRead(key, value, b"Y") self._ExpectRead(key, value, b"Z") with self.assertRaisesOpError("is closed and has insufficient elements " "\\(requested 1, current size 0\\)"): self.evaluate([key, value]) self.assertAllEqual(3, self.evaluate(produced)) self.assertEqual(bytes, type(state)) with self.assertRaises(ValueError): reader.restore_state([]) with self.assertRaises(ValueError): reader.restore_state([state, state]) with self.assertRaisesOpError( "Could not parse state for IdentityReader 'test_reader'"): self.evaluate(reader.restore_state(state[1:])) with self.assertRaisesOpError( "Could not parse state for IdentityReader 'test_reader'"): self.evaluate(reader.restore_state(state[:-1])) with self.assertRaisesOpError( "Could not parse state for IdentityReader 'test_reader'"): self.evaluate(reader.restore_state(state + b"ExtraJunk")) with self.assertRaisesOpError( "Could not parse state for IdentityReader 'test_reader'"): self.evaluate(reader.restore_state(b"PREFIX" + state)) with self.assertRaisesOpError( "Could not parse state for IdentityReader 'test_reader'"): self.evaluate(reader.restore_state(b"BOGUS" + state[5:])) @test_util.run_deprecated_v1 def testReset(self): reader = io_ops.IdentityReader("test_reader") work_completed = reader.num_work_units_completed() produced = reader.num_records_produced() queue = data_flow_ops.FIFOQueue(99, [dtypes.string], shapes=()) queued_length = queue.size() key, value = reader.read(queue) self.evaluate(queue.enqueue_many([["X", "Y", "Z"]])) self._ExpectRead(key, value, b"X") self.assertLess(0, self.evaluate(queued_length)) self.assertAllEqual(1, self.evaluate(produced)) self._ExpectRead(key, value, b"Y") self.assertLess(0, self.evaluate(work_completed)) self.assertAllEqual(2, self.evaluate(produced)) self.evaluate(reader.reset()) self.assertAllEqual(0, self.evaluate(work_completed)) self.assertAllEqual(0, self.evaluate(produced)) self.assertAllEqual(1, self.evaluate(queued_length)) self._ExpectRead(key, value, b"Z") self.evaluate(queue.enqueue_many([["K", "L"]])) self._ExpectRead(key, value, b"K")
IdentityReaderTest
python
redis__redis-py
redis/commands/timeseries/info.py
{ "start": 66, "end": 3223 }
class ____: """ Hold information and statistics on the time-series. Can be created using ``tsinfo`` command https://redis.io/docs/latest/commands/ts.info/ """ rules = [] labels = [] sourceKey = None chunk_count = None memory_usage = None total_samples = None retention_msecs = None last_time_stamp = None first_time_stamp = None max_samples_per_chunk = None chunk_size = None duplicate_policy = None def __init__(self, args): """ Hold information and statistics on the time-series. The supported params that can be passed as args: rules: A list of compaction rules of the time series. sourceKey: Key name for source time series in case the current series is a target of a rule. chunkCount: Number of Memory Chunks used for the time series. memoryUsage: Total number of bytes allocated for the time series. totalSamples: Total number of samples in the time series. labels: A list of label-value pairs that represent the metadata labels of the time series. retentionTime: Retention time, in milliseconds, for the time series. lastTimestamp: Last timestamp present in the time series. firstTimestamp: First timestamp present in the time series. maxSamplesPerChunk: Deprecated. chunkSize: Amount of memory, in bytes, allocated for data. duplicatePolicy: Policy that will define handling of duplicate samples. Can read more about on https://redis.io/docs/latest/develop/data-types/timeseries/configuration/#duplicate_policy """ response = dict(zip(map(nativestr, args[::2]), args[1::2])) self.rules = response.get("rules") self.source_key = response.get("sourceKey") self.chunk_count = response.get("chunkCount") self.memory_usage = response.get("memoryUsage") self.total_samples = response.get("totalSamples") self.labels = list_to_dict(response.get("labels")) self.retention_msecs = response.get("retentionTime") self.last_timestamp = response.get("lastTimestamp") self.first_timestamp = response.get("firstTimestamp") if "maxSamplesPerChunk" in response: self.max_samples_per_chunk = response["maxSamplesPerChunk"] self.chunk_size = ( self.max_samples_per_chunk * 16 ) # backward compatible changes if "chunkSize" in response: self.chunk_size = response["chunkSize"] if "duplicatePolicy" in response: self.duplicate_policy = response["duplicatePolicy"] if isinstance(self.duplicate_policy, bytes): self.duplicate_policy = self.duplicate_policy.decode() def get(self, item): try: return self.__getitem__(item) except AttributeError: return None def __getitem__(self, item): return getattr(self, item)
TSInfo
python
getlogbook__logbook
benchmark/bench_logging_noop_filter.py
{ "start": 183, "end": 465 }
class ____(Filter): def filter(self, record): return False def run(): out = StringIO() handler = StreamHandler(out) handler.addFilter(DisableFilter()) log.addHandler(handler) for _ in range(500): log.warning("this is not handled")
DisableFilter
python
allegroai__clearml
clearml/backend_api/services/v2_20/models.py
{ "start": 22631, "end": 23856 }
class ____(Response): """ Response of models.add_or_update_metadata endpoint. :param updated: Number of models updated (0 or 1) :type updated: int """ _service = "models" _action = "add_or_update_metadata" _version = "2.20" _schema = { "definitions": {}, "properties": { "updated": { "description": "Number of models updated (0 or 1)", "enum": [0, 1], "type": ["integer", "null"], } }, "type": "object", } def __init__(self, updated: Optional[int] = None, **kwargs: Any) -> None: super(AddOrUpdateMetadataResponse, self).__init__(**kwargs) self.updated = updated @schema_property("updated") def updated(self) -> Optional[int]: return self._property_updated @updated.setter def updated(self, value: Optional[int]) -> None: if value is None: self._property_updated = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "updated", six.integer_types) self._property_updated = value
AddOrUpdateMetadataResponse
python
marshmallow-code__marshmallow
tests/test_registry.py
{ "start": 4724, "end": 4844 }
class ____(Schema): id = fields.Integer() b = fields.Nested("tests.test_registry.BSchema", exclude=("a",))
ASchema
python
pytest-dev__pytest
src/_pytest/pytester.py
{ "start": 53993, "end": 62389 }
class ____: """Flexible matching of text. This is a convenience class to test large texts like the output of commands. The constructor takes a list of lines without their trailing newlines, i.e. ``text.splitlines()``. """ def __init__(self, lines: list[str]) -> None: self.lines = lines self._log_output: list[str] = [] def __str__(self) -> str: """Return the entire original text. .. versionadded:: 6.2 You can use :meth:`str` in older versions. """ return "\n".join(self.lines) def _getlines(self, lines2: str | Sequence[str] | Source) -> Sequence[str]: if isinstance(lines2, str): lines2 = Source(lines2) if isinstance(lines2, Source): lines2 = lines2.strip().lines return lines2 def fnmatch_lines_random(self, lines2: Sequence[str]) -> None: """Check lines exist in the output in any order (using :func:`python:fnmatch.fnmatch`).""" __tracebackhide__ = True self._match_lines_random(lines2, fnmatch) def re_match_lines_random(self, lines2: Sequence[str]) -> None: """Check lines exist in the output in any order (using :func:`python:re.match`).""" __tracebackhide__ = True self._match_lines_random(lines2, lambda name, pat: bool(re.match(pat, name))) def _match_lines_random( self, lines2: Sequence[str], match_func: Callable[[str, str], bool] ) -> None: __tracebackhide__ = True lines2 = self._getlines(lines2) for line in lines2: for x in self.lines: if line == x or match_func(x, line): self._log("matched: ", repr(line)) break else: msg = f"line {line!r} not found in output" self._log(msg) self._fail(msg) def get_lines_after(self, fnline: str) -> Sequence[str]: """Return all lines following the given line in the text. The given line can contain glob wildcards. """ for i, line in enumerate(self.lines): if fnline == line or fnmatch(line, fnline): return self.lines[i + 1 :] raise ValueError(f"line {fnline!r} not found in output") def _log(self, *args) -> None: self._log_output.append(" ".join(str(x) for x in args)) @property def _log_text(self) -> str: return "\n".join(self._log_output) def fnmatch_lines( self, lines2: Sequence[str], *, consecutive: bool = False ) -> None: """Check lines exist in the output (using :func:`python:fnmatch.fnmatch`). The argument is a list of lines which have to match and can use glob wildcards. If they do not match a pytest.fail() is called. The matches and non-matches are also shown as part of the error message. :param lines2: String patterns to match. :param consecutive: Match lines consecutively? """ __tracebackhide__ = True self._match_lines(lines2, fnmatch, "fnmatch", consecutive=consecutive) def re_match_lines( self, lines2: Sequence[str], *, consecutive: bool = False ) -> None: """Check lines exist in the output (using :func:`python:re.match`). The argument is a list of lines which have to match using ``re.match``. If they do not match a pytest.fail() is called. The matches and non-matches are also shown as part of the error message. :param lines2: string patterns to match. :param consecutive: match lines consecutively? """ __tracebackhide__ = True self._match_lines( lines2, lambda name, pat: bool(re.match(pat, name)), "re.match", consecutive=consecutive, ) def _match_lines( self, lines2: Sequence[str], match_func: Callable[[str, str], bool], match_nickname: str, *, consecutive: bool = False, ) -> None: """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``. :param Sequence[str] lines2: List of string patterns to match. The actual format depends on ``match_func``. :param match_func: A callable ``match_func(line, pattern)`` where line is the captured line from stdout/stderr and pattern is the matching pattern. :param str match_nickname: The nickname for the match function that will be logged to stdout when a match occurs. :param consecutive: Match lines consecutively? """ if not isinstance(lines2, collections.abc.Sequence): raise TypeError(f"invalid type for lines2: {type(lines2).__name__}") lines2 = self._getlines(lines2) lines1 = self.lines[:] extralines = [] __tracebackhide__ = True wnick = len(match_nickname) + 1 started = False for line in lines2: nomatchprinted = False while lines1: nextline = lines1.pop(0) if line == nextline: self._log("exact match:", repr(line)) started = True break elif match_func(nextline, line): self._log(f"{match_nickname}:", repr(line)) self._log( "{:>{width}}".format("with:", width=wnick), repr(nextline) ) started = True break else: if consecutive and started: msg = f"no consecutive match: {line!r}" self._log(msg) self._log( "{:>{width}}".format("with:", width=wnick), repr(nextline) ) self._fail(msg) if not nomatchprinted: self._log( "{:>{width}}".format("nomatch:", width=wnick), repr(line) ) nomatchprinted = True self._log("{:>{width}}".format("and:", width=wnick), repr(nextline)) extralines.append(nextline) else: msg = f"remains unmatched: {line!r}" self._log(msg) self._fail(msg) self._log_output = [] def no_fnmatch_line(self, pat: str) -> None: """Ensure captured lines do not match the given pattern, using ``fnmatch.fnmatch``. :param str pat: The pattern to match lines. """ __tracebackhide__ = True self._no_match_line(pat, fnmatch, "fnmatch") def no_re_match_line(self, pat: str) -> None: """Ensure captured lines do not match the given pattern, using ``re.match``. :param str pat: The regular expression to match lines. """ __tracebackhide__ = True self._no_match_line( pat, lambda name, pat: bool(re.match(pat, name)), "re.match" ) def _no_match_line( self, pat: str, match_func: Callable[[str, str], bool], match_nickname: str ) -> None: """Ensure captured lines does not have a the given pattern, using ``fnmatch.fnmatch``. :param str pat: The pattern to match lines. """ __tracebackhide__ = True nomatch_printed = False wnick = len(match_nickname) + 1 for line in self.lines: if match_func(line, pat): msg = f"{match_nickname}: {pat!r}" self._log(msg) self._log("{:>{width}}".format("with:", width=wnick), repr(line)) self._fail(msg) else: if not nomatch_printed: self._log("{:>{width}}".format("nomatch:", width=wnick), repr(pat)) nomatch_printed = True self._log("{:>{width}}".format("and:", width=wnick), repr(line)) self._log_output = [] def _fail(self, msg: str) -> None: __tracebackhide__ = True log_text = self._log_text self._log_output = [] fail(log_text) def str(self) -> str: """Return the entire original text.""" return str(self)
LineMatcher
python
getsentry__sentry
src/sentry/sentry_apps/api/serializers/servicehookproject.py
{ "start": 157, "end": 363 }
class ____(Serializer): def serialize(self, obj, attrs, user, **kwargs): return { "id": str(obj.id), "project_id": str(obj.project_id), }
ServiceHookProjectSerializer
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/docstring_code_examples_dynamic_line_width.py
{ "start": 6020, "end": 6880 }
class ____(Abc, Def, Ghi, Jkl, Mno, Pqr, Stu, Vwx, Yz, A1, A2, A3, A4, A5): def abcdefghijklmnopqrstuvwxyz(self, abc, ddef, ghi, jkl, mno, pqr, stu, vwx, yz, a1, a2, a3, a4): def abcdefghijklmnopqrstuvwxyz(abc, ddef, ghi, jkl, mno, pqr, stu, vwx, yz, a1, a2, a3, a4): # For 4 space indents, this is just one character shy of # tripping the default line width of 88. So it should not be # wrapped. print(abc, ddef, ghi, jkl, mno, pqr, stu, vwx, yz, a1, a2, a3, a4, a567) return 5 self.x = doit( 5 ) ``` Done. """ pass # Like unindented, but contains a `print` line where it just barely exceeds the # globally configured line width *after* its indentation has been corrected. def unindented_barely_exceeds_limit(): """ First line. ```py
Abcdefghijklmopqrstuvwxyz
python
doocs__leetcode
solution/1800-1899/1885.Count Pairs in Two Arrays/Solution.py
{ "start": 0, "end": 365 }
class ____: def countPairs(self, nums1: List[int], nums2: List[int]) -> int: nums = [a - b for a, b in zip(nums1, nums2)] nums.sort() l, r = 0, len(nums) - 1 ans = 0 while l < r: while l < r and nums[l] + nums[r] <= 0: l += 1 ans += r - l r -= 1 return ans
Solution
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-sec-filings/llama_index/readers/sec_filings/sec_filings.py
{ "start": 3201, "end": 10797 }
class ____: def __init__( self, tickers: List[str], amount: int, filing_type: str, start_date: str = DEFAULT_AFTER_DATE, end_date: str = DEFAULT_BEFORE_DATE, sections: List[str] = ["_ALL"], include_amends: bool = True, ): """ _summary_. Args: tickers (List[str]): list of ticker amount (int): amount of documenteds filing_type (str): 10-K or 10-Q start_date (str, optional): start date of getting files. Defaults to DEFAULT_AFTER_DATE. end_date (str, optional): end date of getting files. Defaults to DEFAULT_BEFORE_DATE. sections (List[str], optional): sections required, check sections names. Defaults to ["_ALL"]. """ self.tickers = tickers self.amount = amount self.filing_type = filing_type self.start_date = start_date self.end_date = end_date self.sections = sections self.include_amends = include_amends def get_accession_numbers(self, tic: str) -> dict: """ Get accession numbers and download URL for the SEC filing. Args: tic (str): ticker symbol Returns: dict: final dictionary for all the urls and years mentioned """ final_dict = {} filing_metadata = get_filing_urls_to_download( self.filing_type, tic, self.amount, self.start_date, self.end_date, include_amends=self.include_amends, ) # fm.append(filing_metadata) acc_nums_yrs = [ [ self.get_year(fm.filing_details_url), fm.accession_number.replace("-", ""), fm.full_submission_url, ] for fm in filing_metadata ] for idx, fm in enumerate(acc_nums_yrs[:-1]): if fm[0] is None: fm[0] = acc_nums_yrs[idx + 1][0] for acy in acc_nums_yrs: if tic not in final_dict: final_dict.update({tic: []}) final_dict[tic].append( {"year": acy[0], "accession_number": acy[1], "url": acy[2]} ) return final_dict def get_year(self, filing_details: str) -> str: """ Get the year for 10-K and year,month for 10-Q. Args: filing_details (str): filing url Returns: str: year for 10-K and year,month for 10-Q """ details = filing_details.split("/")[-1] if self.filing_type == "10-K": matches = re.findall("20\\d{2}", details) elif self.filing_type == "10-Q": matches = re.findall("20\\d{4}", details) if matches: return matches[-1] # Return the first match else: return None # In case no match is found def get_all_text(self, section, all_narratives): """ Join all the text from a section. Args: section (str): section name all_narratives (dict): dictionary of section names and text Returns: _type_: _description_ """ all_texts = [] for text_dict in all_narratives[section]: for key, val in text_dict.items(): if key == "text": all_texts.append(val) return " ".join(all_texts) def get_text_from_url(self, url: str): """ Get the text from filing document URL. Args: url (str): url link Returns: _type_: all texts of sections and filing type of the document """ text = self.get_filing( url, "Unstructured Technologies", "support@unstructured.io" ) all_narratives, filing_type = self.pipeline_api(text, m_section=self.sections) all_narrative_dict = dict.fromkeys(all_narratives.keys()) for section in all_narratives: all_narrative_dict[section] = self.get_all_text(section, all_narratives) return all_narrative_dict, filing_type def pipeline_api(self, text, m_section=[], m_section_regex=[]): """ Unsturcured API to get the text. Args: text (str): Text from the filing document URL m_section (list, optional): Section required. Defaults to []. m_section_regex (list, optional): Custom Section required using regex . Defaults to []. Raises: ValueError: Invalid document names ValueError: Invalid section names Returns: section and corresponding texts """ validate_section_names(m_section) sec_document = SECDocument.from_string(text) if sec_document.filing_type not in VALID_FILING_TYPES: raise ValueError( f"SEC document filing type {sec_document.filing_type} is not supported," f" must be one of {','.join(VALID_FILING_TYPES)}" ) results = {} if m_section == [ALL_SECTIONS]: filing_type = sec_document.filing_type if filing_type in REPORT_TYPES: if filing_type.startswith("10-K"): m_section = [enum.name for enum in SECTIONS_10K] elif filing_type.startswith("10-Q"): m_section = [enum.name for enum in SECTIONS_10Q] else: raise ValueError(f"Invalid report type: {filing_type}") else: m_section = [enum.name for enum in SECTIONS_S1] for section in m_section: results[section] = sec_document.get_section_narrative( section_string_to_enum[section] ) for i, section_regex in enumerate(m_section_regex): regex_num = get_regex_enum(section_regex) with timeout(seconds=5): section_elements = sec_document.get_section_narrative(regex_num) results[f"REGEX_{i}"] = section_elements return { section: convert_to_isd(section_narrative) for section, section_narrative in results.items() }, sec_document.filing_type @sleep_and_retry @limits(calls=10, period=1) def get_filing(self, url: str, company: str, email: str) -> str: """ Fetches the specified filing from the SEC EDGAR Archives. Conforms to the rate limits specified on the SEC website. ref: https://www.sec.gov/os/accessing-edgar-data. """ session = self._get_session(company, email) response = session.get(url) response.raise_for_status() return response.text def _get_session( self, company: Optional[str] = None, email: Optional[str] = None ) -> requests.Session: """ Creates a requests sessions with the appropriate headers set. If these headers are not set, SEC will reject your request. ref: https://www.sec.gov/os/accessing-edgar-data. """ if company is None: company = os.environ.get("SEC_API_ORGANIZATION") if email is None: email = os.environ.get("SEC_API_EMAIL") assert company assert email session = requests.Session() session.headers.update( { "User-Agent": f"{company} {email}", "Content-Type": "text/html", "Host": "www.sec.gov", } ) return session
SECExtractor
python
huggingface__transformers
src/transformers/models/video_llama_3/image_processing_video_llama_3_fast.py
{ "start": 2949, "end": 12473 }
class ____(BaseImageProcessorFast): do_resize = True resample = PILImageResampling.BICUBIC size = {"shortest_edge": 56 * 56, "longest_edge": 28 * 28 * 1280} do_rescale = True do_normalize = True image_mean = IMAGENET_STANDARD_MEAN image_std = IMAGENET_STANDARD_STD do_convert_rgb = True patch_size = 14 temporal_patch_size = 1 merge_size = 1 min_pixels = None max_pixels = None valid_kwargs = VideoLlama3ImageProcessorKwargs model_input_names = [ "pixel_values", "image_grid_thw", "image_merge_sizes", ] def __init__(self, **kwargs: Unpack[VideoLlama3ImageProcessorKwargs]): size = kwargs.pop("size", None) min_pixels = kwargs.pop("min_pixels", None) max_pixels = kwargs.pop("max_pixels", None) # backward compatibility: override size with min_pixels and max_pixels if they are provided size = self.size if size is None else size if min_pixels is not None: size["shortest_edge"] = min_pixels size.pop("min_pixels", None) if max_pixels is not None: size["longest_edge"] = max_pixels size.pop("max_pixels", None) if "shortest_edge" not in size or "longest_edge" not in size: raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.") super().__init__(size=size, min_pixels=min_pixels, max_pixels=max_pixels, **kwargs) def _further_process_kwargs( self, size: Optional[SizeDict] = None, min_pixels: Optional[int] = None, max_pixels: Optional[int] = None, **kwargs, ) -> dict: """ Update kwargs that need further processing before being validated Can be overridden by subclasses to customize the processing of kwargs. """ if min_pixels is not None and max_pixels is not None: size = {"shortest_edge": min_pixels, "longest_edge": max_pixels} elif size is not None: if "shortest_edge" not in size or "longest_edge" not in size: raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.") min_pixels = size["shortest_edge"] max_pixels = size["longest_edge"] else: size = {**self.size} return super()._further_process_kwargs(size=size, min_pixels=min_pixels, max_pixels=max_pixels, **kwargs) @auto_docstring def preprocess( self, images: ImageInput, **kwargs: Unpack[VideoLlama3ImageProcessorKwargs], ) -> BatchFeature: return super().preprocess(images, **kwargs) def _preprocess_image_like_inputs( self, images: ImageInput, do_convert_rgb: bool, input_data_format: ChannelDimension, device: Optional[Union[str, "torch.device"]] = None, **kwargs: Unpack[VideoLlama3ImageProcessorKwargs], ) -> BatchFeature: """ Preprocess image-like inputs. To be overridden by subclasses when image-like inputs other than images should be processed. It can be used for segmentation maps, depth maps, etc. """ # Prepare input images batch_feature = BatchFeature() if kwargs["temporal_patch_size"] != 1: raise ValueError("`temporal_patch_size` must be 1 for VideoLLaMA3") images = self._prepare_image_like_inputs( images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device ) batch_feature = self._preprocess(images, **kwargs) batch_feature["image_merge_sizes"] = torch.tensor( [kwargs["merge_size"]] * batch_feature.image_grid_thw.size(0), dtype=batch_feature.image_grid_thw.dtype, device=batch_feature.image_grid_thw.device, ) return batch_feature def _preprocess( self, images: list["torch.Tensor"], do_resize: bool, size: SizeDict, interpolation: Optional["F.InterpolationMode"], do_rescale: bool, rescale_factor: float, do_normalize: bool, image_mean: Optional[Union[float, list[float]]], image_std: Optional[Union[float, list[float]]], patch_size: int, temporal_patch_size: int, merge_size: int, disable_grouping: Optional[bool], return_tensors: Optional[Union[str, TensorType]], **kwargs, ): # Group images by size for batched resizing grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): height, width = stacked_images.shape[-2:] if do_resize: resized_height, resized_width = smart_resize( height, width, factor=patch_size * merge_size, min_pixels=size["shortest_edge"], max_pixels=size["longest_edge"], ) stacked_images = self.resize( image=stacked_images, size=SizeDict(height=resized_height, width=resized_width), interpolation=interpolation, ) resized_images_grouped[shape] = stacked_images resized_images = reorder_images(resized_images_grouped, grouped_images_index) # Group images by size for further processing # Needed in case do_resize is False, or resize returns images with different sizes grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping) processed_images_grouped = {} processed_grids = {} for shape, stacked_images in grouped_images.items(): resized_height, resized_width = stacked_images.shape[-2:] # Fused rescale and normalize patches = self.rescale_and_normalize( stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std ) if patches.ndim == 4: # add a temporal dimension if we have images patches = patches.unsqueeze(1) if patches.shape[1] % temporal_patch_size != 0: repeats = patches[:, -1:].repeat(1, temporal_patch_size - 1, 1, 1, 1) patches = torch.cat([patches, repeats], dim=1) batch_size, grid_t, channel = patches.shape[:3] grid_t = grid_t // temporal_patch_size grid_h, grid_w = resized_height // patch_size, resized_width // patch_size patches = patches.view( batch_size, grid_t, temporal_patch_size, channel, grid_h // merge_size, merge_size, patch_size, grid_w // merge_size, merge_size, patch_size, ) # Reorder dimensions to group grid and patch information for subsequent flattening. # (batch, grid_t, grid_h, grid_w, merge_h, merge_w, channel, temp_patch_size, patch_h, patch_w) patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9) flatten_patches = patches.reshape( batch_size, grid_t * grid_h * grid_w, channel * temporal_patch_size * patch_size * patch_size, ) processed_images_grouped[shape] = flatten_patches processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size processed_images = reorder_images(processed_images_grouped, grouped_images_index) processed_grids = reorder_images(processed_grids, grouped_images_index) pixel_values = torch.cat(processed_images, dim=0) image_grid_thw = torch.tensor(processed_grids) return BatchFeature( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None): """ A utility that returns number of image patches for a given image size. Note: Do not remove this method! It is used by vLLM to infer the number of patches and placeholders without an image input. Args: height (`int`): Height of the input image. width (`int`): Width of the input image. images_kwargs (`dict`, *optional*) Any kwargs to override defaults of the image processor. Returns: `int`: Number of image patches per image. """ min_pixels = images_kwargs["min_pixels"] if "min_pixels" in images_kwargs else self.size["shortest_edge"] max_pixels = images_kwargs["max_pixels"] if "max_pixels" in images_kwargs else self.size["longest_edge"] patch_size = images_kwargs.get("patch_size", self.patch_size) merge_size = images_kwargs.get("merge_size", self.merge_size) factor = patch_size * merge_size resized_height, resized_width = smart_resize( height, width, factor, min_pixels=min_pixels, max_pixels=max_pixels ) grid_h, grid_w = resized_height // patch_size, resized_width // patch_size return grid_h * grid_w __all__ = ["VideoLlama3ImageProcessorFast"]
VideoLlama3ImageProcessorFast
python
doocs__leetcode
lcof/面试题05. 替换空格/Solution.py
{ "start": 0, "end": 96 }
class ____: def replaceSpace(self, s: str) -> str: return s.replace(' ', '%20')
Solution
python
TheAlgorithms__Python
data_structures/linked_list/rotate_to_the_right.py
{ "start": 83, "end": 4104 }
class ____: data: int next_node: Node | None = None def print_linked_list(head: Node | None) -> None: """ Print the entire linked list iteratively. This function prints the elements of a linked list separated by '->'. Parameters: head (Node | None): The head of the linked list to be printed, or None if the linked list is empty. >>> head = insert_node(None, 0) >>> head = insert_node(head, 2) >>> head = insert_node(head, 1) >>> print_linked_list(head) 0->2->1 >>> head = insert_node(head, 4) >>> head = insert_node(head, 5) >>> print_linked_list(head) 0->2->1->4->5 """ if head is None: return while head.next_node is not None: print(head.data, end="->") head = head.next_node print(head.data) def insert_node(head: Node | None, data: int) -> Node: """ Insert a new node at the end of a linked list and return the new head. Parameters: head (Node | None): The head of the linked list. data (int): The data to be inserted into the new node. Returns: Node: The new head of the linked list. >>> head = insert_node(None, 10) >>> head = insert_node(head, 9) >>> head = insert_node(head, 8) >>> print_linked_list(head) 10->9->8 """ new_node = Node(data) # If the linked list is empty, the new_node becomes the head if head is None: return new_node temp_node = head while temp_node.next_node: temp_node = temp_node.next_node temp_node.next_node = new_node return head def rotate_to_the_right(head: Node, places: int) -> Node: """ Rotate a linked list to the right by places times. Parameters: head: The head of the linked list. places: The number of places to rotate. Returns: Node: The head of the rotated linked list. >>> rotate_to_the_right(None, places=1) Traceback (most recent call last): ... ValueError: The linked list is empty. >>> head = insert_node(None, 1) >>> rotate_to_the_right(head, places=1) == head True >>> head = insert_node(None, 1) >>> head = insert_node(head, 2) >>> head = insert_node(head, 3) >>> head = insert_node(head, 4) >>> head = insert_node(head, 5) >>> new_head = rotate_to_the_right(head, places=2) >>> print_linked_list(new_head) 4->5->1->2->3 """ # Check if the list is empty or has only one element if not head: raise ValueError("The linked list is empty.") if head.next_node is None: return head # Calculate the length of the linked list length = 1 temp_node = head while temp_node.next_node is not None: length += 1 temp_node = temp_node.next_node # Adjust the value of places to avoid places longer than the list. places %= length if places == 0: return head # As no rotation is needed. # Find the new head position after rotation. new_head_index = length - places # Traverse to the new head position temp_node = head for _ in range(new_head_index - 1): assert temp_node.next_node temp_node = temp_node.next_node # Update pointers to perform rotation assert temp_node.next_node new_head = temp_node.next_node temp_node.next_node = None temp_node = new_head while temp_node.next_node: temp_node = temp_node.next_node temp_node.next_node = head assert new_head return new_head if __name__ == "__main__": import doctest doctest.testmod() head = insert_node(None, 5) head = insert_node(head, 1) head = insert_node(head, 2) head = insert_node(head, 4) head = insert_node(head, 3) print("Original list: ", end="") print_linked_list(head) places = 3 new_head = rotate_to_the_right(head, places) print(f"After {places} iterations: ", end="") print_linked_list(new_head)
Node
python
facebookresearch__faiss
demos/demo_distributed_kmeans_torch.py
{ "start": 366, "end": 5427 }
class ____(clustering.DatasetAssign): """ There is one instance per worker, each worker has a dataset shard. The non-master workers do not run through the k-means function, so some code has run it to keep the workers in sync. """ def __init__(self, res, x, rank, nproc): clustering.DatasetAssign.__init__(self, x) self.res = res self.rank = rank self.nproc = nproc self.device = x.device n = len(x) sizes = torch.zeros(nproc, device=self.device, dtype=torch.int64) sizes[rank] = n torch.distributed.all_gather( [sizes[i:i + 1] for i in range(nproc)], sizes[rank:rank + 1]) self.sizes = sizes.cpu().numpy() # begin & end of each shard self.cs = np.zeros(nproc + 1, dtype='int64') self.cs[1:] = np.cumsum(self.sizes) def count(self): return int(self.sizes.sum()) def int_to_slaves(self, i): " broadcast an int to all workers " rank = self.rank tab = torch.zeros(1, device=self.device, dtype=torch.int64) if rank == 0: tab[0] = i else: assert i is None torch.distributed.broadcast(tab, 0) return tab.item() def get_subset(self, indices): rank = self.rank assert rank == 0 or indices is None len_indices = self.int_to_slaves(len(indices) if rank == 0 else None) if rank == 0: indices = torch.from_numpy(indices).to(self.device) else: indices = torch.zeros( len_indices, dtype=torch.int64, device=self.device) torch.distributed.broadcast(indices, 0) # select subset of indices i0, i1 = self.cs[rank], self.cs[rank + 1] mask = torch.logical_and(indices < i1, indices >= i0) output = torch.zeros( len_indices, self.x.shape[1], dtype=self.x.dtype, device=self.device) output[mask] = self.x[indices[mask] - i0] torch.distributed.reduce(output, 0) # sum if rank == 0: return output else: return None def perform_search(self, centroids): assert False, "should not be called" def assign_to(self, centroids, weights=None): assert weights is None rank, nproc = self.rank, self.nproc assert rank == 0 or centroids is None nc = self.int_to_slaves(len(centroids) if rank == 0 else None) if rank != 0: centroids = torch.zeros( nc, self.x.shape[1], dtype=self.x.dtype, device=self.device) torch.distributed.broadcast(centroids, 0) # perform search D, I = faiss.knn_gpu( self.res, self.x, centroids, 1, device=self.device.index) I = I.ravel() D = D.ravel() sum_per_centroid = torch.zeros_like(centroids) if weights is None: sum_per_centroid.index_add_(0, I, self.x) else: sum_per_centroid.index_add_(0, I, self.x * weights[:, None]) torch.distributed.reduce(sum_per_centroid, 0) if rank == 0: # gather deos not support tensors of different sizes # should be implemented with point-to-point communication assert np.all(self.sizes == self.sizes[0]) device = self.device all_I = torch.zeros(self.count(), dtype=I.dtype, device=device) all_D = torch.zeros(self.count(), dtype=D.dtype, device=device) torch.distributed.gather( I, [all_I[self.cs[r]:self.cs[r + 1]] for r in range(nproc)], dst=0, ) torch.distributed.gather( D, [all_D[self.cs[r]:self.cs[r + 1]] for r in range(nproc)], dst=0, ) return all_I.cpu().numpy(), all_D, sum_per_centroid else: torch.distributed.gather(I, None, dst=0) torch.distributed.gather(D, None, dst=0) return None if __name__ == "__main__": torch.distributed.init_process_group( backend="nccl", ) rank = torch.distributed.get_rank() nproc = torch.distributed.get_world_size() # current version does only support shards of the same size ds = datasets.SyntheticDataset(32, 10000, 0, 0, seed=1234 + rank) x = ds.get_train() device = torch.device(f"cuda:{rank}") torch.cuda.set_device(device) x = torch.from_numpy(x).to(device) res = faiss.StandardGpuResources() da = DatasetAssignDistributedGPU(res, x, rank, nproc) k = 1000 niter = 25 if rank == 0: print(f"sizes = {da.sizes}") centroids, iteration_stats = clustering.kmeans( k, da, niter=niter, return_stats=True) print("clusters:", centroids.cpu().numpy()) else: # make sure the iterations are aligned with master da.get_subset(None) for _ in range(niter): da.assign_to(None) torch.distributed.barrier() print("Done")
DatasetAssignDistributedGPU
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 30867, "end": 31417 }
class ____(HTTPClientError): """ subclass of :class:`~HTTPClientError` This indicates that the server is unable to process the contained instructions. May be used to notify the client that their JSON/XML is well formed, but not correct for the current request. See RFC4918 section 11 for more information. code: 422, title: Unprocessable Entity """ # Note: from WebDAV code = 422 title = 'Unprocessable Entity' explanation = 'Unable to process the contained instructions'
HTTPUnprocessableEntity
python
crytic__slither
slither/tools/read_storage/read_storage.py
{ "start": 2742, "end": 37547 }
class ____: def __init__(self, contracts: List[Contract], max_depth: int, rpc_info: RpcInfo = None) -> None: self._checksum_address: Optional[ChecksumAddress] = None self._contracts: List[Contract] = contracts self._log: str = "" self._max_depth: int = max_depth self._slot_info: Dict[str, SlotInfo] = {} self._target_variables: List[Tuple[Contract, StateVariable]] = [] self._constant_storage_slots: List[Tuple[Contract, StateVariable]] = [] self.rpc_info: Optional[RpcInfo] = rpc_info self.storage_address: Optional[str] = None self.table: Optional[MyPrettyTable] = None self.unstructured: bool = False @property def contracts(self) -> List[Contract]: return self._contracts @property def max_depth(self) -> int: return int(self._max_depth) @property def log(self) -> str: return self._log @log.setter def log(self, log: str) -> None: self._log = log @property def checksum_address(self) -> ChecksumAddress: if not self.storage_address: raise ValueError if not self._checksum_address: self._checksum_address = to_checksum_address(self.storage_address) return self._checksum_address @property def target_variables(self) -> List[Tuple[Contract, StateVariable]]: """Storage variables (not constant or immutable) and their associated contract.""" return self._target_variables @property def constant_slots(self) -> List[Tuple[Contract, StateVariable]]: """Constant bytes32 variables and their associated contract.""" return self._constant_storage_slots @property def slot_info(self) -> Dict[str, SlotInfo]: """Contains the location, type, size, offset, and value of contract slots.""" return self._slot_info def get_storage_layout(self) -> None: """Retrieves the storage layout of entire contract.""" tmp: Dict[str, SlotInfo] = {} for contract, var in self.target_variables: type_ = var.type info = self.get_storage_slot(var, contract) if info: tmp[var.name] = info if isinstance(type_, UserDefinedType) and isinstance(type_.type, Structure): tmp[var.name].elems = self._all_struct_slots(var, type_.type, contract) elif isinstance(type_, ArrayType): elems = self._all_array_slots(var, contract, type_, info.slot) tmp[var.name].elems = elems if self.unstructured: tmp.update(self.get_unstructured_layout()) self._slot_info = tmp def get_unstructured_layout(self) -> Dict[str, SlotInfo]: tmp: Dict[str, SlotInfo] = {} for _, var in self.constant_slots: var_name = var.name try: exp = var.expression if isinstance( exp, ( BinaryOperation, UnaryOperation, Identifier, TupleExpression, TypeConversion, CallExpression, ), ): exp = ConstantFolding(exp, "bytes32").result() if isinstance(exp, Literal): slot = coerce_type("int", exp.value) else: continue offset = 0 type_string, size = self.find_constant_slot_storage_type(var) if type_string: tmp[var.name] = SlotInfo( name=var_name, type_string=type_string, slot=slot, size=size, offset=offset ) self.log += ( f"\nSlot Name: {var_name}\nType: bytes32" f"\nStorage Type: {type_string}\nSlot: {str(exp)}\n" ) logger.info(self.log) self.log = "" except NotConstant: continue return tmp # TODO: remove this pylint exception (montyly) # pylint: disable=too-many-locals def get_storage_slot( self, target_variable: StateVariable, contract: Contract, **kwargs: Any, ) -> Union[SlotInfo, None]: """ Finds the storage slot of a variable in a given contract. Args: target_variable (`StateVariable`): The variable to retrieve the slot for. contracts (`Contract`): The contract that contains the given state variable. **kwargs: key (int): Key of a mapping or index position if an array. deep_key (int): Key of a mapping embedded within another mapping or secondary index if array. struct_var (str): Structure variable name. Returns: (`SlotInfo`) | None : A dictionary of the slot information. """ key: Optional[int] = kwargs.get("key", None) deep_key: Optional[int] = kwargs.get("deep_key", None) struct_var: Optional[str] = kwargs.get("struct_var", None) info: str var_log_name = target_variable.name try: int_slot, size, offset, type_to = self.get_variable_info(contract, target_variable) except KeyError: # Only the child contract of a parent contract will show up in the storage layout when inheritance is used logger.info( f"\nContract {contract} not found in storage layout. It is possibly a parent contract\n" ) return None slot = int.to_bytes(int_slot, 32, byteorder="big") target_variable_type = target_variable.type if isinstance(target_variable_type, ElementaryType): type_to = target_variable_type.name elif isinstance(target_variable_type, ArrayType) and key is not None: var_log_name = f"{var_log_name}[{key}]" info, type_to, slot, size, offset = self._find_array_slot( target_variable_type, slot, key, deep_key=deep_key, struct_var=struct_var, ) self.log += info elif isinstance(target_variable_type, UserDefinedType) and struct_var is not None: var_log_name = f"{var_log_name}.{struct_var}" target_variable_type_type = target_variable_type.type assert isinstance(target_variable_type_type, Structure) elems = target_variable_type_type.elems_ordered info, type_to, slot, size, offset = self._find_struct_var_slot(elems, slot, struct_var) self.log += info elif isinstance(target_variable_type, MappingType) and key: info, type_to, slot, size, offset = self._find_mapping_slot( target_variable_type, slot, key, struct_var=struct_var, deep_key=deep_key ) self.log += info int_slot = int.from_bytes(slot, byteorder="big") self.log += f"\nName: {var_log_name}\nType: {type_to}\nSlot: {int_slot}\n" logger.info(self.log) self.log = "" return SlotInfo( name=var_log_name, type_string=type_to, slot=int_slot, size=size, offset=offset, ) def get_target_variables(self, **kwargs) -> None: """ Retrieves every instance of a given variable in a list of contracts. Should be called after setting `target_variables` with `get_all_storage_variables()`. **kwargs: key (str): Key of a mapping or index position if an array. deep_key (str): Key of a mapping embedded within another mapping or secondary index if array. struct_var (str): Structure variable name. """ for contract, var in self.target_variables: slot_info = self.get_storage_slot(var, contract, **kwargs) if slot_info: self._slot_info[f"{contract.name}.{var.name}"] = slot_info def find_constant_slot_storage_type( self, var: StateVariable ) -> Tuple[Optional[str], Optional[int]]: """ Given a constant bytes32 StateVariable, tries to determine which variable type is stored there, using the heuristic that if a function reads from the slot and returns a value, it probably stores that type of value. Also uses the StorageSlot library as a heuristic when a function has no return but uses the library's getters. Args: var (StateVariable): The constant bytes32 storage slot. Returns: type (str): The type of value stored in the slot. size (int): The type's size in bits. """ assert var.is_constant and var.type == ElementaryType("bytes32") storage_type = None size = None funcs = [] for c in self.contracts: c_funcs = c.get_functions_reading_from_variable(var) c_funcs.extend( f for f in c.functions if any(str(v.expression) == str(var.expression) for v in f.variables) ) c_funcs = list(set(c_funcs)) funcs.extend(c_funcs) fallback = [f for f in var.contract.functions if f.is_fallback] funcs += fallback for func in funcs: rets = func.return_type if func.return_type is not None else [] for ret in rets: size, _ = ret.storage_size if size <= 32: return str(ret), size * 8 for node in func.all_nodes(): exp = node.expression # Look for use of the common OpenZeppelin StorageSlot library if f"getAddressSlot({var.name})" in str(exp): return "address", 160 if f"getBooleanSlot({var.name})" in str(exp): return "bool", 1 if f"getBytes32Slot({var.name})" in str(exp): return "bytes32", 256 if f"getUint256Slot({var.name})" in str(exp): return "uint256", 256 # Look for variable assignment in assembly loaded from a hardcoded slot if ( isinstance(exp, AssignmentOperation) and isinstance(exp.expression_left, Identifier) and isinstance(exp.expression_right, CallExpression) and "sload" in str(exp.expression_right.called) and str(exp.expression_right.arguments[0]) == str(var.expression) ): if func.is_fallback: return "address", 160 storage_type = exp.expression_left.value.type.name size, _ = exp.expression_left.value.type.storage_size return storage_type, size * 8 # Look for variable storage in assembly stored to a hardcoded slot if ( isinstance(exp, CallExpression) and "sstore" in str(exp.called) and isinstance(exp.arguments[0], Identifier) and isinstance(exp.arguments[1], Identifier) and str(exp.arguments[0].value.expression) == str(var.expression) ): storage_type = exp.arguments[1].value.type.name size, _ = exp.arguments[1].value.type.storage_size return storage_type, size * 8 return storage_type, size def walk_slot_info(self, func: Callable) -> None: stack = list(self.slot_info.values()) while stack: slot_info = stack.pop() if isinstance(slot_info, dict): # NestedElem stack.extend(slot_info.values()) elif slot_info.elems: stack.extend(list(slot_info.elems.values())) if isinstance(slot_info, SlotInfo): func(slot_info) def get_slot_values(self, slot_info: SlotInfo) -> None: """ Fetches the slot value of `SlotInfo` object :param slot_info: """ assert self.rpc_info is not None hex_bytes = get_storage_data( self.rpc_info.web3, self.checksum_address, int.to_bytes(slot_info.slot, 32, byteorder="big"), self.rpc_info.block, ) slot_info.value = self.convert_value_to_type( hex_bytes, slot_info.size, slot_info.offset, slot_info.type_string ) logger.info(f"\nValue: {slot_info.value}\n") def get_all_storage_variables(self, func: Callable = lambda x: x) -> None: """ Fetches all storage variables from a list of contracts. kwargs: func (Callable, optional): A criteria to filter functions e.g. name. """ for contract in self.contracts: for var in contract.state_variables_ordered: if func(var): if var.is_stored: self._target_variables.append((contract, var)) elif ( self.unstructured and var.is_constant and var.type == ElementaryType("bytes32") ): self._constant_storage_slots.append((contract, var)) if self.unstructured: hardcoded_slot = self.find_hardcoded_slot_in_fallback(contract) if hardcoded_slot is not None: self._constant_storage_slots.append((contract, hardcoded_slot)) def find_hardcoded_slot_in_fallback(self, contract: Contract) -> Optional[StateVariable]: """ Searches the contract's fallback function for a sload from a literal storage slot, i.e., `let contractLogic := sload(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7)`. Args: contract: a Contract object, which should have a fallback function. Returns: A newly created StateVariable representing the Literal bytes32 slot, if one is found, otherwise None. """ fallback = None for func in contract.functions_entry_points: if func.is_fallback: fallback = func break if fallback is None: return None queue = [fallback.entry_point] visited = [] while len(queue) > 0: node = queue.pop(0) visited.append(node) queue.extend(son for son in node.sons if son not in visited) if node.type == NodeType.ASSEMBLY and isinstance(node.inline_asm, str): return SlitherReadStorage.find_hardcoded_slot_in_asm_str(node.inline_asm, contract) if node.type == NodeType.EXPRESSION: sv = self.find_hardcoded_slot_in_exp(node.expression, contract) if sv is not None: return sv return None @staticmethod def find_hardcoded_slot_in_asm_str( inline_asm: str, contract: Contract ) -> Optional[StateVariable]: """ Searches a block of assembly code (given as a string) for a sload from a literal storage slot. Does not work if the argument passed to sload does not start with "0x", i.e., `sload(add(1,1))` or `and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)`. Args: inline_asm: a string containing all the code in an assembly node (node.inline_asm for solc < 0.6.0). Returns: A newly created StateVariable representing the Literal bytes32 slot, if one is found, otherwise None. """ asm_split = inline_asm.split("\n") for asm in asm_split: if "sload(" in asm: # Only handle literals arg = asm.split("sload(")[1].split(")")[0] if arg.startswith("0x"): exp = Literal(arg, ElementaryType("bytes32")) sv = StateVariable() sv.name = "fallback_sload_hardcoded" sv.expression = exp sv.is_constant = True sv.type = exp.type sv.set_contract(contract) return sv return None def find_hardcoded_slot_in_exp( self, exp: "Expression", contract: Contract ) -> Optional[StateVariable]: """ Parses an expression to see if it contains a sload from a literal storage slot, unrolling nested expressions if necessary to determine which slot it loads from. Args: exp: an Expression object to search. contract: the Contract containing exp. Returns: A newly created StateVariable representing the Literal bytes32 slot, if one is found, otherwise None. """ if isinstance(exp, AssignmentOperation): exp = exp.expression_right while isinstance(exp, BinaryOperation): exp = next( (e for e in exp.expressions if isinstance(e, (CallExpression, BinaryOperation))), exp.expression_left, ) while isinstance(exp, CallExpression) and len(exp.arguments) > 0: called = exp.called exp = exp.arguments[0] if "sload" in str(called): break if isinstance( exp, ( BinaryOperation, UnaryOperation, Identifier, TupleExpression, TypeConversion, CallExpression, ), ): try: exp = ConstantFolding(exp, "bytes32").result() except NotConstant: return None if ( isinstance(exp, Literal) and isinstance(exp.type, ElementaryType) and exp.type.name in ["bytes32", "uint256"] ): sv = StateVariable() sv.name = "fallback_sload_hardcoded" value = exp.value str_value = str(value) if str_value.isdecimal(): value = int(value) if isinstance(value, (int, bytes)): if isinstance(value, bytes): str_value = "0x" + value.hex() value = int(str_value, 16) exp = Literal(str_value, ElementaryType("bytes32")) state_var_slots = [ self.get_variable_info(contract, var)[0] for contract, var in self.target_variables ] if value in state_var_slots: return None sv.expression = exp sv.is_constant = True sv.type = ElementaryType("bytes32") sv.set_contract(contract) return sv return None def convert_slot_info_to_rows(self, slot_info: SlotInfo) -> None: """ Convert and append slot info to table. Create table if it does not yet exist :param slot_info: """ field_names = [ field.name for field in dataclasses.fields(SlotInfo) if field.name != "elems" ] if not self.table: self.table = MyPrettyTable(field_names) self.table.add_row([getattr(slot_info, field) for field in field_names]) def to_json(self) -> Dict: return {key: dataclasses.asdict(value) for key, value in self.slot_info.items()} @staticmethod def _find_struct_var_slot( elems: List[StructureVariable], slot_as_bytes: bytes, struct_var: str ) -> Tuple[str, str, bytes, int, int]: """ Finds the slot of a structure variable. Args: elems (List[StructureVariable]): Ordered list of structure variables. slot_as_bytes (bytes): The slot of the struct to begin searching at. struct_var (str): The target structure variable. Returns: info (str): Info about the target variable to log. type_to (str): The type of the target variable. slot (bytes): The storage location of the target variable. size (int): The size (in bits) of the target variable. offset (int): The size of other variables that share the same slot. """ slot = int.from_bytes(slot_as_bytes, "big") offset = 0 type_to = "" size = 0 for var in elems: var_type = var.type if isinstance(var_type, ElementaryType): size = var_type.size if size > (256 - offset): slot += 1 offset = 0 if struct_var == var.name: type_to = var_type.name break # found struct var offset += size else: logger.info(f"{type(var_type)} is current not implemented in _find_struct_var_slot") slot_as_bytes = int.to_bytes(slot, 32, byteorder="big") info = f"\nStruct Variable: {struct_var}" return info, type_to, slot_as_bytes, size, offset # pylint: disable=too-many-branches,too-many-statements @staticmethod def _find_array_slot( target_variable_type: ArrayType, slot: bytes, key: int, deep_key: int = None, struct_var: str = None, ) -> Tuple[str, str, bytes, int, int]: """ Finds the slot of array's index. Args: target_variable (`StateVariable`): The array that contains the target variable. slot (bytes): The starting slot of the array. key (int): The target variable's index position. deep_key (int, optional): Secondary index if nested array. struct_var (str, optional): Structure variable name. Returns: info (str): Info about the target variable to log. type_to (str): The type of the target variable. slot (bytes): The storage location of the target variable. size (int): The size offset (int): The offset """ info = f"\nKey: {key}" offset = 0 size = 256 target_variable_type_type = target_variable_type.type if isinstance( target_variable_type_type, ArrayType ): # multidimensional array uint[i][], , uint[][i], or uint[][] assert isinstance(target_variable_type_type.type, ElementaryType) size = target_variable_type_type.type.size type_to = target_variable_type_type.type.name if target_variable_type.is_fixed_array: # uint[][i] slot_int = int.from_bytes(slot, "big") + int(key) else: slot = keccak(slot) key = int(key) if target_variable_type_type.is_fixed_array: # arr[i][] key *= int(str(target_variable_type_type.length)) slot_int = int.from_bytes(slot, "big") + key if not deep_key: return info, type_to, int.to_bytes(slot_int, 32, "big"), size, offset info += f"\nDeep Key: {deep_key}" if target_variable_type_type.is_dynamic_array: # uint[][] # keccak256(keccak256(slot) + index) + floor(j / floor(256 / size)) slot = keccak(int.to_bytes(slot_int, 32, "big")) slot_int = int.from_bytes(slot, "big") # keccak256(slot) + index + floor(j / floor(256 / size)) slot_int += floor(int(deep_key) / floor(256 / size)) # uint[i][] elif target_variable_type.is_fixed_array: slot_int = int.from_bytes(slot, "big") + int(key) if isinstance(target_variable_type_type, UserDefinedType) and isinstance( target_variable_type_type.type, Structure ): # struct[i] type_to = target_variable_type_type.type.name if not struct_var: return info, type_to, int.to_bytes(slot_int, 32, "big"), size, offset elems = target_variable_type_type.type.elems_ordered slot = int.to_bytes(slot_int, 32, byteorder="big") info_tmp, type_to, slot, size, offset = SlitherReadStorage._find_struct_var_slot( elems, slot, struct_var ) info += info_tmp else: assert isinstance(target_variable_type_type, ElementaryType) type_to = target_variable_type_type.name size = target_variable_type_type.size # bits elif isinstance(target_variable_type_type, UserDefinedType) and isinstance( target_variable_type_type.type, Structure ): # struct[] slot = keccak(slot) slot_int = int.from_bytes(slot, "big") + int(key) type_to = target_variable_type_type.type.name if not struct_var: return info, type_to, int.to_bytes(slot_int, 32, "big"), size, offset elems = target_variable_type_type.type.elems_ordered slot = int.to_bytes(slot_int, 32, byteorder="big") info_tmp, type_to, slot, size, offset = SlitherReadStorage._find_struct_var_slot( elems, slot, struct_var ) info += info_tmp else: assert isinstance(target_variable_type_type, ElementaryType) slot = keccak(slot) slot_int = int.from_bytes(slot, "big") + int(key) type_to = target_variable_type_type.name size = target_variable_type_type.size # bits slot = int.to_bytes(slot_int, 32, byteorder="big") return info, type_to, slot, size, offset @staticmethod def _find_mapping_slot( target_variable_type: MappingType, slot: bytes, key: Union[int, str], deep_key: Union[int, str] = None, struct_var: str = None, ) -> Tuple[str, str, bytes, int, int]: """ Finds the data slot of a target variable within a mapping. target_variable (`StateVariable`): The mapping that contains the target variable. slot (bytes): The starting slot of the mapping. key (Union[int, str]): The key the variable is stored at. deep_key (int, optional): Key of a mapping embedded within another mapping. struct_var (str, optional): Structure variable name. :returns: log (str): Info about the target variable to log. type_to (str): The type of the target variable. slot (bytes): The storage location of the target variable. size (int): The size (in bits) of the target variable. offset (int): The size of other variables that share the same slot. """ info = "" offset = 0 if key: info += f"\nKey: {key}" if deep_key: info += f"\nDeep Key: {deep_key}" assert isinstance(target_variable_type.type_from, ElementaryType) key_type = target_variable_type.type_from.name assert key if "int" in key_type: # without this eth_utils encoding fails key = int(key) key = coerce_type(key_type, key) slot = keccak(encode([key_type, "uint256"], [key, decode(["uint256"], slot)[0]])) if isinstance(target_variable_type.type_to, UserDefinedType) and isinstance( target_variable_type.type_to.type, Structure ): # mapping(elem => struct) assert struct_var elems = target_variable_type.type_to.type.elems_ordered info_tmp, type_to, slot, size, offset = SlitherReadStorage._find_struct_var_slot( elems, slot, struct_var ) info += info_tmp elif isinstance( target_variable_type.type_to, MappingType ): # mapping(elem => mapping(elem => ???)) assert deep_key assert isinstance(target_variable_type.type_to.type_from, ElementaryType) key_type = target_variable_type.type_to.type_from.name if "int" in key_type: # without this eth_utils encoding fails deep_key = int(deep_key) # If deep map, will be keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot))))) slot = keccak(encode([key_type, "bytes32"], [deep_key, slot])) # mapping(elem => mapping(elem => elem)) target_variable_type_type_to_type_to = target_variable_type.type_to.type_to assert isinstance( target_variable_type_type_to_type_to, (UserDefinedType, ElementaryType) ) type_to = str(target_variable_type_type_to_type_to.type) byte_size, _ = target_variable_type_type_to_type_to.storage_size size = byte_size * 8 # bits offset = 0 if isinstance(target_variable_type_type_to_type_to, UserDefinedType) and isinstance( target_variable_type_type_to_type_to.type, Structure ): # mapping(elem => mapping(elem => struct)) assert struct_var elems = target_variable_type_type_to_type_to.type.elems_ordered # If map struct, will be bytes32(uint256(keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))))) + structFieldDepth); info_tmp, type_to, slot, size, offset = SlitherReadStorage._find_struct_var_slot( elems, slot, struct_var ) info += info_tmp # TODO: support mapping with dynamic arrays # mapping(elem => elem) elif isinstance(target_variable_type.type_to, ElementaryType): type_to = target_variable_type.type_to.name # the value's elementary type byte_size, _ = target_variable_type.type_to.storage_size size = byte_size * 8 # bits else: raise NotImplementedError( f"{target_variable_type} => {target_variable_type.type_to} not implemented" ) return info, type_to, slot, size, offset @staticmethod def get_variable_info( contract: Contract, target_variable: StateVariable ) -> Tuple[int, int, int, str]: """Return slot, size, offset, and type.""" assert isinstance(target_variable.type, Type) type_to = str(target_variable.type) byte_size, _ = target_variable.type.storage_size size = byte_size * 8 # bits (int_slot, offset) = contract.compilation_unit.storage_layout_of(contract, target_variable) offset *= 8 # bits logger.info( f"\nContract '{contract.name}'\n{target_variable.canonical_name} with type {target_variable.type} is located at slot: {int_slot}\n" ) return int_slot, size, offset, type_to @staticmethod def convert_value_to_type( hex_bytes: bytes, size: int, offset: int, type_to: str ) -> Union[int, bool, str, ChecksumAddress]: """Convert slot data to type representation.""" # Account for storage packing offset_hex_bytes = get_offset_value(hex_bytes, offset, size) try: value = coerce_type(type_to, offset_hex_bytes) except ValueError: return coerce_type("int", offset_hex_bytes) return value def _all_struct_slots( self, var: StateVariable, st: Structure, contract: Contract, key: Optional[int] = None ) -> Elem: """Retrieves all members of a struct.""" struct_elems = st.elems_ordered data: Elem = {} for elem in struct_elems: info = self.get_storage_slot( var, contract, key=key, struct_var=elem.name, ) if info: data[elem.name] = info return data # pylint: disable=too-many-nested-blocks def _all_array_slots( self, var: StateVariable, contract: Contract, type_: ArrayType, slot: int ) -> Union[Elem, NestedElem]: """Retrieves all members of an array.""" array_length = self._get_array_length(type_, slot) target_variable_type = type_.type if isinstance(target_variable_type, UserDefinedType) and isinstance( target_variable_type.type, Structure ): nested_elems: NestedElem = {} for i in range(min(array_length, self.max_depth)): nested_elems[str(i)] = self._all_struct_slots( var, target_variable_type.type, contract, key=i ) return nested_elems elems: Elem = {} for i in range(min(array_length, self.max_depth)): info = self.get_storage_slot( var, contract, key=str(i), ) if info: elems[str(i)] = info if isinstance(target_variable_type, ArrayType): # multidimensional array array_length = self._get_array_length(target_variable_type, info.slot) for j in range(min(array_length, self.max_depth)): info = self.get_storage_slot( var, contract, key=str(i), deep_key=str(j), ) if info: elems[str(i)].elems[str(j)] = info return elems def _get_array_length(self, type_: Type, slot: int) -> int: """ Gets the length of dynamic and fixed arrays. Args: type_ (`AbstractType`): The array type. slot (int): Slot a dynamic array's length is stored at. Returns: (int): The length of the array. """ val = 0 if self.rpc_info: # The length of dynamic arrays is stored at the starting slot. # Convert from hexadecimal to decimal. val = int( get_storage_data( self.rpc_info.web3, self.checksum_address, int.to_bytes(slot, 32, byteorder="big"), self.rpc_info.block, ).hex(), 16, ) if isinstance(type_, ArrayType): if type_.is_fixed_array: val = int(str(type_.length)) return val
SlitherReadStorage
python
jina-ai__jina
setup.py
{ "start": 2766, "end": 2921 }
class ____(develop): """Post-installation for development mode.""" def run(self): develop.run(self) register_ac()
PostDevelopCommand
python
streamlit__streamlit
lib/streamlit/elements/lib/column_types.py
{ "start": 3537, "end": 3719 }
class ____(TypedDict): type: Literal["link"] max_chars: NotRequired[int | None] validate: NotRequired[str | None] display_text: NotRequired[str | None]
LinkColumnConfig
python
facelessuser__pymdown-extensions
tests/test_extensions/test_blocks/test_general_blocks.py
{ "start": 9402, "end": 10447 }
class ____(util.MdCase): """Test Blocks tab cases.""" extension = ['pymdownx.blocks.admonition'] def test_attributes(self): """Test attributes.""" self.check_markdown( R''' /// admonition | Title attrs: {class: some classes, id: an-id, name: some value} content /// ''', ''' <div class="admonition some classes" id="an-id" name="some value"> <p class="admonition-title">Title</p> <p>content</p> </div> ''', True ) def test_bad_attributes(self): """Test no attributes.""" self.check_markdown( R''' /// admonition | Title attrs: {'+': 'value'} content /// ''', ''' <p>/// admonition | Title attrs: {'+': 'value'} content ///</p> ''', True )
TestAttributes
python
getsentry__sentry
src/sentry/shared_integrations/exceptions/__init__.py
{ "start": 4223, "end": 4273 }
class ____(ApiError): code = 401
ApiUnauthorized