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
pydata__xarray
xarray/coding/times.py
{ "start": 50932, "end": 56041 }
class ____(VariableCoder): """Coder for CF Datetime coding. Parameters ---------- use_cftime : bool, optional Only relevant if encoded dates come from a standard calendar (e.g. "gregorian", "proleptic_gregorian", "standard", or not specified). If None (default), attempt to decode times to ``np.datetime64`` objects; if this is not possible, decode times to ``cftime.datetime`` objects. If True, always decode times to ``cftime.datetime`` objects, regardless of whether or not they can be represented using ``np.datetime64`` objects. If False, always decode times to ``np.datetime64`` objects; if this is not possible raise an error. May not be supported by all the backends. time_unit : PDDatetimeUnitOptions Target resolution when decoding dates. Defaults to "ns". """ def __init__( self, use_cftime: bool | None = None, time_unit: PDDatetimeUnitOptions = "ns", ) -> None: self.use_cftime = use_cftime self.time_unit = time_unit def encode(self, variable: Variable, name: T_Name = None) -> Variable: if np.issubdtype( variable.data.dtype, np.datetime64 ) or contains_cftime_datetimes(variable): dims, data, attrs, encoding = unpack_for_encoding(variable) units = encoding.pop("units", None) calendar = encoding.pop("calendar", None) dtype = encoding.get("dtype", None) # in the case of packed data we need to encode into # float first, the correct dtype will be established # via CFScaleOffsetCoder/CFMaskCoder if "add_offset" in encoding or "scale_factor" in encoding: dtype = data.dtype if data.dtype.kind == "f" else "float64" (data, units, calendar) = encode_cf_datetime(data, units, calendar, dtype) safe_setitem(attrs, "units", units, name=name) safe_setitem(attrs, "calendar", calendar, name=name) return Variable(dims, data, attrs, encoding, fastpath=True) else: return variable def decode(self, variable: Variable, name: T_Name = None) -> Variable: units = variable.attrs.get("units", None) if isinstance(units, str) and "since" in units: dims, data, attrs, encoding = unpack_for_decoding(variable) units = pop_to(attrs, encoding, "units") calendar = pop_to(attrs, encoding, "calendar") dtype = _decode_cf_datetime_dtype( data, units, calendar, self.use_cftime, self.time_unit ) transform = partial( decode_cf_datetime, units=units, calendar=calendar, use_cftime=self.use_cftime, time_unit=self.time_unit, ) data = lazy_elemwise_func(data, transform, dtype) return Variable(dims, data, attrs, encoding, fastpath=True) else: return variable def has_timedelta64_encoding_dtype(attrs_or_encoding: dict) -> bool: dtype = attrs_or_encoding.get("dtype") return isinstance(dtype, str) and dtype.startswith("timedelta64") def resolve_time_unit_from_attrs_dtype( attrs_dtype: str, name: T_Name ) -> PDDatetimeUnitOptions: dtype = np.dtype(attrs_dtype) resolution, _ = np.datetime_data(dtype) resolution = cast(NPDatetimeUnitOptions, resolution) time_unit: PDDatetimeUnitOptions if np.timedelta64(1, resolution) > np.timedelta64(1, "s"): time_unit = "s" message = ( f"Following pandas, xarray only supports decoding to timedelta64 " f"values with a resolution of 's', 'ms', 'us', or 'ns'. Encoded " f"values for variable {name!r} have a resolution of " f"{resolution!r}. Attempting to decode to a resolution of 's'. " f"Note, depending on the encoded values, this may lead to an " f"OverflowError. Additionally, data will not be identically round " f"tripped; xarray will choose an encoding dtype of " f"'timedelta64[s]' when re-encoding." ) emit_user_level_warning(message) elif np.timedelta64(1, resolution) < np.timedelta64(1, "ns"): time_unit = "ns" message = ( f"Following pandas, xarray only supports decoding to timedelta64 " f"values with a resolution of 's', 'ms', 'us', or 'ns'. Encoded " f"values for variable {name!r} have a resolution of " f"{resolution!r}. Attempting to decode to a resolution of 'ns'. " f"Note, depending on the encoded values, this may lead to loss of " f"precision. Additionally, data will not be identically round " f"tripped; xarray will choose an encoding dtype of " f"'timedelta64[ns]' when re-encoding." ) emit_user_level_warning(message) else: time_unit = cast(PDDatetimeUnitOptions, resolution) return time_unit
CFDatetimeCoder
python
huggingface__transformers
src/transformers/models/dia/modeling_dia.py
{ "start": 2279, "end": 2641 }
class ____(PreTrainedModel): config: DiaConfig base_model_prefix = "model" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _can_compile_fullgraph = True main_input_name = "input_ids" _no_split_modules = ["DiaEncoderLayer", "DiaDecoderLayer"]
DiaPreTrainedModel
python
pytorch__pytorch
torch/nn/utils/spectral_norm.py
{ "start": 10496, "end": 14936 }
class ____: # See docstring of SpectralNorm._version on the changes to spectral_norm. def __init__(self, fn) -> None: self.fn = fn def __call__(self, module, state_dict, prefix, local_metadata) -> None: if "spectral_norm" not in local_metadata: local_metadata["spectral_norm"] = {} key = self.fn.name + ".version" if key in local_metadata["spectral_norm"]: raise RuntimeError(f"Unexpected key in metadata['spectral_norm']: {key}") local_metadata["spectral_norm"][key] = self.fn._version T_module = TypeVar("T_module", bound=Module) def spectral_norm( module: T_module, name: str = "weight", n_power_iterations: int = 1, eps: float = 1e-12, dim: int | None = None, ) -> T_module: r"""Apply spectral normalization to a parameter in the given module. .. math:: \mathbf{W}_{SN} = \dfrac{\mathbf{W}}{\sigma(\mathbf{W})}, \sigma(\mathbf{W}) = \max_{\mathbf{h}: \mathbf{h} \ne 0} \dfrac{\|\mathbf{W} \mathbf{h}\|_2}{\|\mathbf{h}\|_2} Spectral normalization stabilizes the training of discriminators (critics) in Generative Adversarial Networks (GANs) by rescaling the weight tensor with spectral norm :math:`\sigma` of the weight matrix calculated using power iteration method. If the dimension of the weight tensor is greater than 2, it is reshaped to 2D in power iteration method to get spectral norm. This is implemented via a hook that calculates spectral norm and rescales weight before every :meth:`~Module.forward` call. See `Spectral Normalization for Generative Adversarial Networks`_ . .. _`Spectral Normalization for Generative Adversarial Networks`: https://arxiv.org/abs/1802.05957 Args: module (nn.Module): containing module name (str, optional): name of weight parameter n_power_iterations (int, optional): number of power iterations to calculate spectral norm eps (float, optional): epsilon for numerical stability in calculating norms dim (int, optional): dimension corresponding to number of outputs, the default is ``0``, except for modules that are instances of ConvTranspose{1,2,3}d, when it is ``1`` Returns: The original module with the spectral norm hook .. note:: This function has been reimplemented as :func:`torch.nn.utils.parametrizations.spectral_norm` using the new parametrization functionality in :func:`torch.nn.utils.parametrize.register_parametrization`. Please use the newer version. This function will be deprecated in a future version of PyTorch. Example:: >>> m = spectral_norm(nn.Linear(20, 40)) >>> m Linear(in_features=20, out_features=40, bias=True) >>> m.weight_u.size() torch.Size([40]) """ if dim is None: if isinstance( module, ( torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d, ), ): dim = 1 else: dim = 0 SpectralNorm.apply(module, name, n_power_iterations, dim, eps) # pyrefly: ignore [bad-return] return module def remove_spectral_norm(module: T_module, name: str = "weight") -> T_module: r"""Remove the spectral normalization reparameterization from a module. Args: module (Module): containing module name (str, optional): name of weight parameter Example: >>> m = spectral_norm(nn.Linear(40, 10)) >>> remove_spectral_norm(m) """ for k, hook in module._forward_pre_hooks.items(): if isinstance(hook, SpectralNorm) and hook.name == name: hook.remove(module) del module._forward_pre_hooks[k] break else: raise ValueError(f"spectral_norm of '{name}' not found in {module}") for k, hook in module._state_dict_hooks.items(): if isinstance(hook, SpectralNormStateDictHook) and hook.fn.name == name: del module._state_dict_hooks[k] break for k, hook in module._load_state_dict_pre_hooks.items(): if isinstance(hook, SpectralNormLoadStateDictPreHook) and hook.fn.name == name: del module._load_state_dict_pre_hooks[k] break return module
SpectralNormStateDictHook
python
getsentry__sentry-python
sentry_sdk/logger.py
{ "start": 505, "end": 2797 }
class ____(dict): # type: ignore[type-arg] """dict that returns the key if missing.""" def __missing__(self, key): # type: (str) -> str return "{" + key + "}" def _capture_log(severity_text, severity_number, template, **kwargs): # type: (str, int, str, **Any) -> None client = get_client() body = template attrs = {} # type: dict[str, str | bool | float | int] if "attributes" in kwargs: attrs.update(kwargs.pop("attributes")) for k, v in kwargs.items(): attrs[f"sentry.message.parameter.{k}"] = v if kwargs: # only attach template if there are parameters attrs["sentry.message.template"] = template with capture_internal_exceptions(): body = template.format_map(_dict_default_key(kwargs)) attrs = { k: ( v if ( isinstance(v, str) or isinstance(v, int) or isinstance(v, bool) or isinstance(v, float) ) else safe_repr(v) ) for (k, v) in attrs.items() } # noinspection PyProtectedMember client._capture_log( { "severity_text": severity_text, "severity_number": severity_number, "attributes": attrs, "body": body, "time_unix_nano": time.time_ns(), "trace_id": None, }, ) trace = functools.partial(_capture_log, "trace", 1) debug = functools.partial(_capture_log, "debug", 5) info = functools.partial(_capture_log, "info", 9) warning = functools.partial(_capture_log, "warn", 13) error = functools.partial(_capture_log, "error", 17) fatal = functools.partial(_capture_log, "fatal", 21) def _otel_severity_text(otel_severity_number): # type: (int) -> str for (lower, upper), severity in OTEL_RANGES: if lower <= otel_severity_number <= upper: return severity return "default" def _log_level_to_otel(level, mapping): # type: (int, dict[Any, int]) -> tuple[int, str] for py_level, otel_severity_number in sorted(mapping.items(), reverse=True): if level >= py_level: return otel_severity_number, _otel_severity_text(otel_severity_number) return 0, "default"
_dict_default_key
python
yandexdataschool__Practical_RL
week06_policy_based/atari_wrappers.py
{ "start": 7831, "end": 10707 }
class ____(Wrapper): """Env summaries writer base.""" def __init__(self, env, prefix=None, running_mean_size=100, step_var=None): super().__init__(env) self.episode_counter = 0 self.prefix = prefix or self.env.spec.id self.step_var = step_var or 0 self.nenvs = getattr(self.env.unwrapped, "nenvs", 1) self.rewards = np.zeros(self.nenvs) self.had_ended_episodes = np.zeros(self.nenvs, dtype=bool) self.episode_lengths = np.zeros(self.nenvs) self.reward_queues = [ deque([], maxlen=running_mean_size) for _ in range(self.nenvs) ] def should_write_summaries(self): """Returns true if it's time to write summaries.""" return np.all(self.had_ended_episodes) def add_summaries(self): """Writes summaries.""" self.add_summary( f"Episodes/total_reward", np.mean([q[-1] for q in self.reward_queues]) ) self.add_summary( f"Episodes/reward_mean_{self.reward_queues[0].maxlen}", np.mean([np.mean(q) for q in self.reward_queues]), ) self.add_summary(f"Episodes/episode_length", np.mean(self.episode_lengths)) if self.had_ended_episodes.size > 1: self.add_summary( f"Episodes/min_reward", min(q[-1] for q in self.reward_queues), ) self.add_summary( f"Episodes/max_reward", max(q[-1] for q in self.reward_queues), ) self.episode_lengths.fill(0) self.had_ended_episodes.fill(False) def step(self, action): obs, rew, terminated, truncated, info = self.env.step(action) self.rewards += rew self.episode_lengths[~self.had_ended_episodes] += 1 info_collection = [info] if isinstance(info, dict) else info terminated_collection = ( [terminated] if isinstance(terminated, bool) else terminated ) truncated_collection = [truncated] if isinstance(truncated, bool) else truncated done_indices = [ i for i, info in enumerate(info_collection) if info.get( "real_done", terminated_collection[i] or truncated_collection[i] ) ] for i in done_indices: if not self.had_ended_episodes[i]: self.had_ended_episodes[i] = True self.reward_queues[i].append(self.rewards[i]) self.rewards[i] = 0 self.step_var += self.nenvs if self.should_write_summaries(): self.add_summaries() return obs, rew, terminated, truncated, info def reset(self, **kwargs): self.rewards.fill(0) self.episode_lengths.fill(0) self.had_ended_episodes.fill(False) return self.env.reset(**kwargs)
SummariesBase
python
numba__numba
numba/core/typing/builtins.py
{ "start": 6131, "end": 6193 }
class ____(BinOp): pass @infer_global(operator.mod)
BinOpMul
python
spyder-ide__spyder
spyder/plugins/remoteclient/api/protocol.py
{ "start": 647, "end": 993 }
class ____(typing.TypedDict): host: str port: int | None username: str password: str | None client_keys: typing.Sequence[str] | None passphrase: str | None known_hosts: str | typing.Sequence[str] | None config: typing.Sequence[str] | None platform: str | None default_kernel_spec: str | None
SSHClientOptions
python
getsentry__sentry-python
sentry_sdk/consts.py
{ "start": 3021, "end": 3228 }
class ____(str, Enum): DEFAULT = "default" AI_AGENT = "ai_agent" AI_TOOL = "ai_tool" AI_CHAT = "ai_chat" def __str__(self): # type: () -> str return self.value
SPANTEMPLATE
python
scrapy__scrapy
tests/test_feedexport.py
{ "start": 103613, "end": 103987 }
class ____(TestURIParams): deprecated_options = False def build_settings(self, uri="file:///tmp/foobar", uri_params=None): options = { "format": "jl", } if uri_params: options["uri_params"] = uri_params return { "FEEDS": { uri: options, }, }
TestURIParamsFeedOption
python
pypa__pipenv
pipenv/patched/pip/_internal/resolution/resolvelib/base.py
{ "start": 3572, "end": 5113 }
class ____: @property def project_name(self) -> NormalizedName: """The "project name" of the candidate. This is different from ``name`` if this candidate contains extras, in which case ``name`` would contain the ``[...]`` part, while this refers to the name of the project. """ raise NotImplementedError("Override in subclass") @property def name(self) -> str: """The name identifying this candidate in the resolver. This is different from ``project_name`` if this candidate contains extras, where ``project_name`` would not contain the ``[...]`` part. """ raise NotImplementedError("Override in subclass") @property def version(self) -> Version: raise NotImplementedError("Override in subclass") @property def is_installed(self) -> bool: raise NotImplementedError("Override in subclass") @property def is_editable(self) -> bool: raise NotImplementedError("Override in subclass") @property def source_link(self) -> Optional[Link]: raise NotImplementedError("Override in subclass") def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]: raise NotImplementedError("Override in subclass") def get_install_requirement(self) -> Optional[InstallRequirement]: raise NotImplementedError("Override in subclass") def format_for_error(self) -> str: raise NotImplementedError("Subclass should override")
Candidate
python
pytorch__pytorch
torch/testing/_internal/common_utils.py
{ "start": 83293, "end": 83985 }
class ____: def __init__(self, always_warn): assert isinstance(always_warn, bool) self.always_warn = always_warn def __enter__(self): self.always_warn_restore = torch.storage._get_always_warn_typed_storage_removal() torch.storage._set_always_warn_typed_storage_removal(self.always_warn) def __exit__(self, exception_type, exception_value, traceback): torch.storage._set_always_warn_typed_storage_removal(self.always_warn_restore) # Context manager for setting cuda sync debug mode and reset it # to original value # we are not exposing it to the core because sync debug mode is # global and thus not thread safe
AlwaysWarnTypedStorageRemoval
python
numba__numba
numba/cuda/simulator/cudadrv/devicearray.py
{ "start": 564, "end": 969 }
class ____(tuple): ''' The FakeShape class is used to provide a shape which does not allow negative indexing, similar to the shape in CUDA Python. (Numpy shape arrays allow negative indexing) ''' def __getitem__(self, k): if isinstance(k, int) and k < 0: raise IndexError('tuple index out of range') return super(FakeShape, self).__getitem__(k)
FakeShape
python
Pylons__pyramid
tests/test_config/test_views.py
{ "start": 145515, "end": 145794 }
class ____: utility = None def __init__(self): self.settings = { 'pyramid.reload_assets': False, } def queryUtility(self, type_or_iface, name=None, default=None): return self.utility or default @implementer(IResponse)
DummyRegistry
python
huggingface__transformers
src/transformers/models/vit/modeling_vit.py
{ "start": 24143, "end": 26078 }
class ____(ViTPreTrainedModel): def __init__(self, config: ViTConfig): super().__init__(config) self.num_labels = config.num_labels self.vit = ViTModel(config, add_pooling_layer=False) # Classifier head self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, pixel_values: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, interpolate_pos_encoding: Optional[bool] = None, **kwargs: Unpack[TransformersKwargs], ) -> ImageClassifierOutput: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the image 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). """ outputs: BaseModelOutputWithPooling = self.vit( pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, **kwargs, ) sequence_output = outputs.last_hidden_state pooled_output = sequence_output[:, 0, :] logits = self.classifier(pooled_output) loss = None if labels is not None: loss = self.loss_function(labels, logits, self.config, **kwargs) return ImageClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = ["ViTForImageClassification", "ViTForMaskedImageModeling", "ViTModel", "ViTPreTrainedModel"]
ViTForImageClassification
python
python-pillow__Pillow
src/PIL/DdsImagePlugin.py
{ "start": 708, "end": 903 }
class ____(IntFlag): CAPS = 0x1 HEIGHT = 0x2 WIDTH = 0x4 PITCH = 0x8 PIXELFORMAT = 0x1000 MIPMAPCOUNT = 0x20000 LINEARSIZE = 0x80000 DEPTH = 0x800000 # DDS caps
DDSD
python
pypa__warehouse
warehouse/integrations/vulnerabilities/__init__.py
{ "start": 232, "end": 2207 }
class ____: def __init__( self, project: str, versions: list[str], vulnerability_id: str, advisory_link: str, aliases: list[str], details: str | None, summary: str | None, fixed_in: list[str], withdrawn: str | None, ): self.project = project self.versions = versions self.vulnerability_id = vulnerability_id self.advisory_link = advisory_link self.aliases = aliases self.details = details self.summary = summary self.fixed_in = fixed_in self.withdrawn = withdrawn @classmethod def from_api_request(cls, request): if not isinstance(request, dict): raise InvalidVulnerabilityReportError( f"Record is not a dict but: {str(request)[:100]}", reason="format" ) missing_keys = sorted( {"project", "versions", "id", "link", "aliases"} - set(request) ) if missing_keys: raise InvalidVulnerabilityReportError( f"Record is missing attribute(s): {', '.join(missing_keys)}", reason="format", ) return cls( project=request["project"], versions=request["versions"], vulnerability_id=request["id"], advisory_link=request["link"], aliases=request["aliases"], details=request.get("details"), summary=request.get("summary"), fixed_in=[ version for event in request.get("events", []) for event_type, version in event.items() if event_type == "fixed" ], withdrawn=request.get("withdrawn"), ) DEFAULT_PUBLIC_KEYS_CACHE_SECONDS = 60 * 30 # 30 minutes DEFAULT_PUBLIC_KEYS_CACHE = integrations.PublicKeysCache( cache_time=DEFAULT_PUBLIC_KEYS_CACHE_SECONDS )
VulnerabilityReportRequest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/oracle/oracledb.py
{ "start": 30923, "end": 31544 }
class ____(OracleExecutionContext_oracledb): # restore default create cursor create_cursor = default.DefaultExecutionContext.create_cursor def create_default_cursor(self): # copy of OracleExecutionContext_cx_oracle.create_cursor c = self._dbapi_connection.cursor() if self.dialect.arraysize: c.arraysize = self.dialect.arraysize return c def create_server_side_cursor(self): c = self._dbapi_connection.ss_cursor() if self.dialect.arraysize: c.arraysize = self.dialect.arraysize return c
OracleExecutionContextAsync_oracledb
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/concepts/io_management/metadata.py
{ "start": 546, "end": 1600 }
class ____(ConfigurableIOManager): def handle_output(self, context: OutputContext, obj): if context.definition_metadata: table_name = context.definition_metadata["table"] schema = context.definition_metadata["schema"] write_dataframe_to_table(name=table_name, schema=schema, dataframe=obj) else: raise Exception( f"op {context.op_def.name} doesn't have schema and metadata set" ) def load_input(self, context: InputContext): if context.upstream_output and context.upstream_output.definition_metadata: table_name = context.upstream_output.definition_metadata["table"] schema = context.upstream_output.definition_metadata["schema"] return read_dataframe_from_table(name=table_name, schema=schema) else: raise Exception("Upstream output doesn't have schema and metadata set") # io_manager_end_marker @job(resource_defs={"io_manager": MyIOManager()}) def my_job(): op_2(op_1())
MyIOManager
python
huggingface__transformers
src/transformers/models/mllama/modeling_mllama.py
{ "start": 25219, "end": 28733 }
class ____(GradientCheckpointingLayer): def __init__(self, config: MllamaTextConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = MllamaTextSelfAttention(config=config, layer_idx=layer_idx) self.mlp = MllamaTextMLP(config) self.input_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.layer_idx = layer_idx def forward( self, hidden_states: torch.Tensor, cross_attention_states: Optional[torch.Tensor] = None, cross_attention_mask: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, full_text_row_masked_out_mask: Optional[tuple[torch.Tensor, torch.Tensor]] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, use_cache: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, query_sequence_length, key_sequence_length)` if default attention is used. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_values (`Cache`, *optional*): cached past key and value projection states cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*): Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`, with `head_dim` being the embedding dimension of each attention head. kwargs (`dict`, *optional*): Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code into the model """ residual = hidden_states hidden_states = self.input_layernorm(hidden_states) # Self Attention hidden_states, self_attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states return hidden_states
MllamaSelfAttentionDecoderLayer
python
python-openxml__python-docx
src/docx/blkcntnr.py
{ "start": 920, "end": 3525 }
class ____(StoryChild): """Base class for proxy objects that can contain block items. These containers include _Body, _Cell, header, footer, footnote, endnote, comment, and text box objects. Provides the shared functionality to add a block item like a paragraph or table. """ def __init__(self, element: BlockItemElement, parent: t.ProvidesStoryPart): super(BlockItemContainer, self).__init__(parent) self._element = element def add_paragraph(self, text: str = "", style: str | ParagraphStyle | None = None) -> Paragraph: """Return paragraph newly added to the end of the content in this container. The paragraph has `text` in a single run if present, and is given paragraph style `style`. If `style` is |None|, no paragraph style is applied, which has the same effect as applying the 'Normal' style. """ paragraph = self._add_paragraph() if text: paragraph.add_run(text) if style is not None: paragraph.style = style return paragraph def add_table(self, rows: int, cols: int, width: Length) -> Table: """Return table of `width` having `rows` rows and `cols` columns. The table is appended appended at the end of the content in this container. `width` is evenly distributed between the table columns. """ from docx.table import Table tbl = CT_Tbl.new_tbl(rows, cols, width) self._element._insert_tbl(tbl) # pyright: ignore[reportPrivateUsage] return Table(tbl, self) def iter_inner_content(self) -> Iterator[Paragraph | Table]: """Generate each `Paragraph` or `Table` in this container in document order.""" from docx.table import Table for element in self._element.inner_content_elements: yield (Paragraph(element, self) if isinstance(element, CT_P) else Table(element, self)) @property def paragraphs(self): """A list containing the paragraphs in this container, in document order. Read-only. """ return [Paragraph(p, self) for p in self._element.p_lst] @property def tables(self): """A list containing the tables in this container, in document order. Read-only. """ from docx.table import Table return [Table(tbl, self) for tbl in self._element.tbl_lst] def _add_paragraph(self): """Return paragraph newly added to the end of the content in this container.""" return Paragraph(self._element.add_p(), self)
BlockItemContainer
python
spack__spack
lib/spack/spack/vendor/six.py
{ "start": 19105, "end": 34562 }
class ____(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ['parse', 'error', 'request', 'response', 'robotparser'] _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from spack.vendor.six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType def create_unbound_method(func, cls): return func Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) def create_unbound_method(func, cls): return types.MethodType(func, None, cls) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) viewkeys = operator.methodcaller("keys") viewvalues = operator.methodcaller("values") viewitems = operator.methodcaller("items") else: def iterkeys(d, **kw): return d.iterkeys(**kw) def itervalues(d, **kw): return d.itervalues(**kw) def iteritems(d, **kw): return d.iteritems(**kw) def iterlists(d, **kw): return d.iterlists(**kw) viewkeys = operator.methodcaller("viewkeys") viewvalues = operator.methodcaller("viewvalues") viewitems = operator.methodcaller("viewitems") _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc(iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: def b(s): return s.encode("latin-1") def u(s): return s unichr = chr import struct int2byte = struct.Struct(">B").pack del struct byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO del io _assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1: _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _assertNotRegex = "assertNotRegexpMatches" else: _assertRaisesRegex = "assertRaisesRegex" _assertRegex = "assertRegex" _assertNotRegex = "assertNotRegex" else: def b(s): return s # Workaround for standalone backslash def u(s): return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) iterbytes = functools.partial(itertools.imap, ord) import StringIO StringIO = BytesIO = StringIO.StringIO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _assertNotRegex = "assertNotRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs) def assertNotRegex(self, *args, **kwargs): return getattr(self, _assertNotRegex)(*args, **kwargs) if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): try: if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value finally: value = None tb = None else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): try: raise tp, value, tb finally: tb = None """) if sys.version_info[:2] > (3,): exec_("""def raise_from(value, from_value): try: raise value from from_value finally: value = None """) else: def raise_from(value, from_value): raise value print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) if sys.version_info[:2] < (3, 3): _print = print_ def print_(*args, **kwargs): fp = kwargs.get("file", sys.stdout) flush = kwargs.pop("flush", False) _print(*args, **kwargs) if flush and fp is not None: fp.flush() _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): # This does exactly the same what the :func:`py3:functools.update_wrapper` # function does on Python versions after 3.2. It sets the ``__wrapped__`` # attribute on ``wrapper`` object and it doesn't raise an error if any of # the attributes mentioned in ``assigned`` and ``updated`` are missing on # ``wrapped`` object. def _update_wrapper(wrapper, wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): for attr in assigned: try: value = getattr(wrapped, attr) except AttributeError: continue else: setattr(wrapper, attr, value) for attr in updated: getattr(wrapper, attr).update(getattr(wrapped, attr, {})) wrapper.__wrapped__ = wrapped return wrapper _update_wrapper.__doc__ = functools.update_wrapper.__doc__ def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): return functools.partial(_update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated) wraps.__doc__ = functools.wraps.__doc__ else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): if sys.version_info[:2] >= (3, 7): # This version introduced PEP 560 that requires a bit # of extra care (we mimic what is done by __build_class__). resolved_bases = types.resolve_bases(bases) if resolved_bases is not bases: d['__orig_bases__'] = bases else: resolved_bases = bases return meta(name, resolved_bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, 'temporary_class', (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) if hasattr(cls, '__qualname__'): orig_vars['__qualname__'] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def ensure_binary(s, encoding='utf-8', errors='strict'): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, binary_type): return s if isinstance(s, text_type): return s.encode(encoding, errors) raise TypeError("not expecting type '%s'" % type(s)) def ensure_str(s, encoding='utf-8', errors='strict'): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ # Optimization: Fast return for the common case. if type(s) is str: return s if PY2 and isinstance(s, text_type): return s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): return s.decode(encoding, errors) elif not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) return s def ensure_text(s, encoding='utf-8', errors='strict'): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def python_2_unicode_compatible(klass): """ A class decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if (type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer)
Module_six_moves_urllib
python
Lightning-AI__lightning
src/lightning/fabric/strategies/ddp.py
{ "start": 10295, "end": 11024 }
class ____(_BackwardSyncControl): @override def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager: """Blocks gradient synchronization inside the :class:`~torch.nn.parallel.distributed.DistributedDataParallel` wrapper.""" if not enabled: return nullcontext() if not isinstance(module, DistributedDataParallel): raise TypeError( "Blocking backward sync is only possible if the module passed to" f" `{self.__class__.__name__}.no_backward_sync` is wrapped in `DistributedDataParallel`." f" Got: {module.__class__.__name__}." ) return module.no_sync()
_DDPBackwardSyncControl
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/plan/objects.py
{ "start": 5050, "end": 5625 }
class ____( NamedTuple( "_StepRetryData", [("error", SerializableErrorInfo), ("seconds_to_wait", Optional[check.Numeric])], ) ): def __new__(cls, error, seconds_to_wait=None): return super().__new__( cls, error=check.not_none( truncate_event_error_info( check.opt_inst_param(error, "error", SerializableErrorInfo) ) ), seconds_to_wait=check.opt_numeric_param(seconds_to_wait, "seconds_to_wait"), ) @whitelist_for_serdes
StepRetryData
python
python-openxml__python-docx
src/docx/oxml/comments.py
{ "start": 518, "end": 3553 }
class ____(BaseOxmlElement): """`w:comments` element, the root element for the comments part. Simply contains a collection of `w:comment` elements, each representing a single comment. Each contained comment is identified by a unique `w:id` attribute, used to reference the comment from the document text. The offset of the comment in this collection is arbitrary; it is essentially a _set_ implemented as a list. """ # -- type-declarations to fill in the gaps for metaclass-added methods -- comment_lst: list[CT_Comment] comment = ZeroOrMore("w:comment") def add_comment(self) -> CT_Comment: """Return newly added `w:comment` child of this `w:comments`. The returned `w:comment` element is the minimum valid value, having a `w:id` value unique within the existing comments and the required `w:author` attribute present but set to the empty string. It's content is limited to a single run containing the necessary annotation reference but no text. Content is added by adding runs to this first paragraph and by adding additional paragraphs as needed. """ next_id = self._next_available_comment_id() comment = cast( CT_Comment, parse_xml( f'<w:comment {nsdecls("w")} w:id="{next_id}" w:author="">' f" <w:p>" f" <w:pPr>" f' <w:pStyle w:val="CommentText"/>' f" </w:pPr>" f" <w:r>" f" <w:rPr>" f' <w:rStyle w:val="CommentReference"/>' f" </w:rPr>" f" <w:annotationRef/>" f" </w:r>" f" </w:p>" f"</w:comment>" ), ) self.append(comment) return comment def get_comment_by_id(self, comment_id: int) -> CT_Comment | None: """Return the `w:comment` element identified by `comment_id`, or |None| if not found.""" comment_elms = self.xpath(f"(./w:comment[@w:id='{comment_id}'])[1]") return comment_elms[0] if comment_elms else None def _next_available_comment_id(self) -> int: """The next available comment id. According to the schema, this can be any positive integer, as big as you like, and the default mechanism is to use `max() + 1`. However, if that yields a value larger than will fit in a 32-bit signed integer, we take a more deliberate approach to use the first ununsed integer starting from 0. """ used_ids = [int(x) for x in self.xpath("./w:comment/@w:id")] next_id = max(used_ids, default=-1) + 1 if next_id <= 2**31 - 1: return next_id # -- fall-back to enumerating all used ids to find the first unused one -- for expected, actual in enumerate(sorted(used_ids)): if expected != actual: return expected return len(used_ids)
CT_Comments
python
facebookresearch__faiss
tests/torch_test_contrib.py
{ "start": 446, "end": 13276 }
class ____(unittest.TestCase): # tests add, search def test_lookup(self): d = 128 index = faiss.IndexFlatL2(d) # Add to CPU index with torch CPU xb_torch = torch.rand(10000, d) index.add(xb_torch) # Test reconstruct y_torch = index.reconstruct(10) self.assertTrue(torch.equal(y_torch, xb_torch[10])) # Add to CPU index with numpy CPU xb_np = torch.rand(500, d).numpy() index.add(xb_np) self.assertEqual(index.ntotal, 10500) y_np = np.zeros(d, dtype=np.float32) index.reconstruct(10100, y_np) self.assertTrue(np.array_equal(y_np, xb_np[100])) # Search with np cpu xq_torch = torch.rand(10, d, dtype=torch.float32) d_np, I_np = index.search(xq_torch.numpy(), 5) # Search with torch cpu d_torch, I_torch = index.search(xq_torch, 5) # The two should be equivalent self.assertTrue(np.array_equal(d_np, d_torch.numpy())) self.assertTrue(np.array_equal(I_np, I_torch.numpy())) # Search with np cpu using pre-allocated arrays d_np_input = np.zeros((10, 5), dtype=np.float32) I_np_input = np.zeros((10, 5), dtype=np.int64) index.search(xq_torch.numpy(), 5, d_np_input, I_np_input) self.assertTrue(np.array_equal(d_np, d_np_input)) self.assertTrue(np.array_equal(I_np, I_np_input)) # Search with torch cpu using pre-allocated arrays d_torch_input = torch.zeros(10, 5, dtype=torch.float32) I_torch_input = torch.zeros(10, 5, dtype=torch.int64) index.search(xq_torch, 5, d_torch_input, I_torch_input) self.assertTrue(np.array_equal(d_torch_input.numpy(), d_np)) self.assertTrue(np.array_equal(I_torch_input.numpy(), I_np)) # tests train, add_with_ids def test_train_add_with_ids(self): d = 32 nlist = 5 quantizer = faiss.IndexFlatL2(d) index = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_L2) xb = torch.rand(1000, d, dtype=torch.float32) index.train(xb) # Test add_with_ids with torch cpu ids = torch.arange(1000, 1000 + xb.shape[0], dtype=torch.int64) index.add_with_ids(xb, ids) _, I = index.search(xb[10:20], 1) self.assertTrue(torch.equal(I.view(10), ids[10:20])) # Test add_with_ids with numpy index.reset() index.train(xb.numpy()) index.add_with_ids(xb.numpy(), ids.numpy()) _, I = index.search(xb.numpy()[10:20], 1) self.assertTrue(np.array_equal(I.reshape(10), ids.numpy()[10:20])) # tests reconstruct, reconstruct_n def test_reconstruct(self): d = 32 index = faiss.IndexFlatL2(d) xb = torch.rand(100, d, dtype=torch.float32) index.add(xb) # Test reconstruct with torch cpu (native return) y = index.reconstruct(7) self.assertTrue(torch.equal(xb[7], y)) # Test reconstruct with numpy output provided y = np.empty(d, dtype=np.float32) index.reconstruct(11, y) self.assertTrue(np.array_equal(xb.numpy()[11], y)) # Test reconstruct with torch cpu output providesd y = torch.empty(d, dtype=torch.float32) index.reconstruct(12, y) self.assertTrue(torch.equal(xb[12], y)) # Test reconstruct_n with torch cpu (native return) y = index.reconstruct_n(10, 10) self.assertTrue(torch.equal(xb[10:20], y)) # Test reconstruct with numpy output provided y = np.empty((10, d), dtype=np.float32) index.reconstruct_n(20, 10, y) self.assertTrue(np.array_equal(xb.cpu().numpy()[20:30], y)) # Test reconstruct_n with torch cpu output provided y = torch.empty(10, d, dtype=torch.float32) index.reconstruct_n(40, 10, y) self.assertTrue(torch.equal(xb[40:50].cpu(), y)) # tests assign def test_assign(self): d = 32 index = faiss.IndexFlatL2(d) xb = torch.rand(1000, d, dtype=torch.float32) index.add(xb) index_ref = faiss.IndexFlatL2(d) index_ref.add(xb.numpy()) # Test assign with native cpu output xq = torch.rand(10, d, dtype=torch.float32) labels = index.assign(xq, 5) labels_ref = index_ref.assign(xq.cpu(), 5) self.assertTrue(torch.equal(labels, labels_ref)) # Test assign with np input labels = index.assign(xq.numpy(), 5) labels_ref = index_ref.assign(xq.numpy(), 5) self.assertTrue(np.array_equal(labels, labels_ref)) # Test assign with numpy output provided labels = np.empty((xq.shape[0], 5), dtype='int64') index.assign(xq.numpy(), 5, labels) self.assertTrue(np.array_equal(labels, labels_ref)) # Test assign with torch cpu output provided labels = torch.empty(xq.shape[0], 5, dtype=torch.int64) index.assign(xq, 5, labels) labels_ref = index_ref.assign(xq, 5) self.assertTrue(torch.equal(labels, labels_ref)) # tests remove_ids def test_remove_ids(self): # only implemented for cpu index + numpy at the moment d = 32 quantizer = faiss.IndexFlatL2(d) index = faiss.IndexIVFFlat(quantizer, d, 5) index.make_direct_map() index.set_direct_map_type(faiss.DirectMap.Hashtable) xb = torch.rand(1000, d, dtype=torch.float32) ids = torch.arange(1000, 1000 + xb.shape[0], dtype=torch.int64) index.train(xb) index.add_with_ids(xb, ids) ids_remove = np.array([1010], dtype=np.int64) index.remove_ids(ids_remove) # We should find this y = index.reconstruct(1011) self.assertTrue(np.array_equal(xb[11].numpy(), y)) # We should not find this with self.assertRaises(RuntimeError): y = index.reconstruct(1010) # Torch not yet supported ids_remove = torch.tensor([1012], dtype=torch.int64) with self.assertRaises(AssertionError): index.remove_ids(ids_remove) # tests update_vectors def test_update_vectors(self): d = 32 quantizer_np = faiss.IndexFlatL2(d) index_np = faiss.IndexIVFFlat(quantizer_np, d, 5) index_np.make_direct_map() index_np.set_direct_map_type(faiss.DirectMap.Hashtable) quantizer_torch = faiss.IndexFlatL2(d) index_torch = faiss.IndexIVFFlat(quantizer_torch, d, 5) index_torch.make_direct_map() index_torch.set_direct_map_type(faiss.DirectMap.Hashtable) xb = torch.rand(1000, d, dtype=torch.float32) ids = torch.arange(1000, 1000 + xb.shape[0], dtype=torch.int64) index_np.train(xb.numpy()) index_np.add_with_ids(xb.numpy(), ids.numpy()) index_torch.train(xb) index_torch.add_with_ids(xb, ids) xb_up = torch.rand(10, d, dtype=torch.float32) ids_up = ids[0:10] index_np.update_vectors(ids_up.numpy(), xb_up.numpy()) index_torch.update_vectors(ids_up, xb_up) xq = torch.rand(10, d, dtype=torch.float32) D_np, I_np = index_np.search(xq.numpy(), 5) D_torch, I_torch = index_torch.search(xq, 5) self.assertTrue(np.array_equal(D_np, D_torch.numpy())) self.assertTrue(np.array_equal(I_np, I_torch.numpy())) # tests range_search def test_range_search(self): torch.manual_seed(10) d = 32 index = faiss.IndexFlatL2(d) xb = torch.rand(100, d, dtype=torch.float32) index.add(xb) # torch cpu as ground truth thresh = 2.9 xq = torch.rand(10, d, dtype=torch.float32) lims, D, I = index.range_search(xq, thresh) # compare against np lims_np, D_np, I_np = index.range_search(xq.numpy(), thresh) self.assertTrue(np.array_equal(lims.numpy(), lims_np)) self.assertTrue(np.array_equal(D.numpy(), D_np)) self.assertTrue(np.array_equal(I.numpy(), I_np)) # tests search_and_reconstruct def test_search_and_reconstruct(self): d = 32 nlist = 10 M = 4 k = 5 quantizer = faiss.IndexFlatL2(d) index = faiss.IndexIVFPQ(quantizer, d, nlist, M, 4) xb = torch.rand(1000, d, dtype=torch.float32) index.train(xb) # different set xb = torch.rand(500, d, dtype=torch.float32) index.add(xb) # torch cpu as ground truth xq = torch.rand(10, d, dtype=torch.float32) D, I, R = index.search_and_reconstruct(xq, k) # compare against numpy D_np, I_np, R_np = index.search_and_reconstruct(xq.numpy(), k) self.assertTrue(np.array_equal(D.numpy(), D_np)) self.assertTrue(np.array_equal(I.numpy(), I_np)) self.assertTrue(np.array_equal(R.numpy(), R_np)) # numpy input values D_input = np.zeros((xq.shape[0], k), dtype=np.float32) I_input = np.zeros((xq.shape[0], k), dtype=np.int64) R_input = np.zeros((xq.shape[0], k, d), dtype=np.float32) index.search_and_reconstruct(xq.numpy(), k, D_input, I_input, R_input) self.assertTrue(np.array_equal(D.numpy(), D_input)) self.assertTrue(np.array_equal(I.numpy(), I_input)) self.assertTrue(np.array_equal(R.numpy(), R_input)) # torch input values D_input = torch.zeros(xq.shape[0], k, dtype=torch.float32) I_input = torch.zeros(xq.shape[0], k, dtype=torch.int64) R_input = torch.zeros(xq.shape[0], k, d, dtype=torch.float32) index.search_and_reconstruct(xq, k, D_input, I_input, R_input) self.assertTrue(torch.equal(D, D_input)) self.assertTrue(torch.equal(I, I_input)) self.assertTrue(torch.equal(R, R_input)) def test_search_preassigned(self): ds = datasets.SyntheticDataset(32, 1000, 100, 10) index = faiss.index_factory(32, "IVF20,PQ4np") index.train(ds.get_train()) index.add(ds.get_database()) index.nprobe = 4 Dref, Iref = index.search(ds.get_queries(), 10) quantizer = faiss.clone_index(index.quantizer) # mutilate the index' quantizer index.quantizer.reset() index.quantizer.add(np.zeros((20, 32), dtype='float32')) # test numpy codepath Dq, Iq = quantizer.search(ds.get_queries(), 4) Dref2, Iref2 = index.search_preassigned(ds.get_queries(), 10, Iq, Dq) np.testing.assert_array_equal(Iref, Iref2) np.testing.assert_array_equal(Dref, Dref2) # test torch codepath xq = torch.from_numpy(ds.get_queries()) Dq, Iq = quantizer.search(xq, 4) Dref2, Iref2 = index.search_preassigned(xq, 10, Iq, Dq) np.testing.assert_array_equal(Iref, Iref2.numpy()) np.testing.assert_array_equal(Dref, Dref2.numpy()) # tests sa_encode, sa_decode def test_sa_encode_decode(self): d = 16 index = faiss.IndexScalarQuantizer(d, faiss.ScalarQuantizer.QT_8bit) xb = torch.rand(1000, d, dtype=torch.float32) index.train(xb) # torch cpu as ground truth nq = 10 xq = torch.rand(nq, d, dtype=torch.float32) encoded_torch = index.sa_encode(xq) # numpy cpu encoded_np = index.sa_encode(xq.numpy()) self.assertTrue(np.array_equal(encoded_torch.numpy(), encoded_np)) decoded_torch = index.sa_decode(encoded_torch) decoded_np = index.sa_decode(encoded_np) self.assertTrue(torch.equal(decoded_torch, torch.from_numpy(decoded_np))) # torch cpu as output parameter encoded_torch_param = torch.zeros(nq, d, dtype=torch.uint8) index.sa_encode(xq, encoded_torch_param) self.assertTrue(torch.equal(encoded_torch, encoded_torch)) decoded_torch_param = torch.zeros(nq, d, dtype=torch.float32) index.sa_decode(encoded_torch, decoded_torch_param) self.assertTrue(torch.equal(decoded_torch, decoded_torch_param)) # np as output parameter encoded_np_param = np.zeros((nq, d), dtype=np.uint8) index.sa_encode(xq.numpy(), encoded_np_param) self.assertTrue(np.array_equal(encoded_torch.numpy(), encoded_np_param)) decoded_np_param = np.zeros((nq, d), dtype=np.float32) index.sa_decode(encoded_np_param, decoded_np_param) self.assertTrue(np.array_equal(decoded_np, decoded_np_param)) def test_non_contiguous(self): d = 128 index = faiss.IndexFlatL2(d) xb = torch.rand(d, 100).transpose(0, 1) with self.assertRaises(AssertionError): index.add(xb) # disabled since we now accept non-contiguous arrays # with self.assertRaises(ValueError): # index.add(xb.numpy())
TestTorchUtilsCPU
python
huggingface__transformers
src/transformers/models/luke/modeling_luke.py
{ "start": 33309, "end": 34672 }
class ____(PreTrainedModel): config: LukeConfig base_model_prefix = "luke" supports_gradient_checkpointing = True _no_split_modules = ["LukeAttention", "LukeEntityEmbeddings"] @torch.no_grad() def _init_weights(self, module: nn.Module): """Initialize the weights""" if isinstance(module, nn.Linear): init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) if module.bias is not None: init.zeros_(module.bias) elif isinstance(module, nn.Embedding): if module.embedding_dim == 1: # embedding for bias parameters init.zeros_(module.weight) else: init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False): init.zeros_(module.weight[module.padding_idx]) elif isinstance(module, nn.LayerNorm): init.zeros_(module.bias) init.ones_(module.weight) @auto_docstring( custom_intro=""" The bare LUKE model transformer outputting raw hidden-states for both word tokens and entities without any """ )
LukePreTrainedModel
python
numba__numba
numba/tests/test_dispatcher.py
{ "start": 38046, "end": 38541 }
class ____(unittest.TestCase): """Test that vectorize can be reapplied if the target is different """ def test_cpu_vs_parallel(self): @jit def add(x, y): return x + y custom_vectorize = vectorize([], identity=None, target='cpu') custom_vectorize(add) custom_vectorize_2 = vectorize([], identity=None, target='parallel') custom_vectorize_2(add) if __name__ == '__main__': unittest.main()
TestVectorizeDifferentTargets
python
davidhalter__parso
parso/utils.py
{ "start": 4628, "end": 4714 }
class ____(NamedTuple): major: int minor: int @total_ordering
_PythonVersionInfo
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/external_data.py
{ "start": 21406, "end": 21742 }
class ____(IHaveNew): partition_names: Sequence[str] def __new__(cls, partition_names: Optional[Sequence[str]] = None): return super().__new__( cls, partition_names=partition_names or [], ) @whitelist_for_serdes(storage_name="ExternalPartitionConfigData") @record_custom
PartitionNamesSnap
python
walkccc__LeetCode
solutions/2401. Longest Nice Subarray/2401.py
{ "start": 0, "end": 273 }
class ____: def longestNiceSubarray(self, nums: list[int]) -> int: ans = 0 used = 0 l = 0 for r, num in enumerate(nums): while used & num: used ^= nums[l] l += 1 used |= num ans = max(ans, r - l + 1) return ans
Solution
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 4269, "end": 6752 }
class ____(BaseModel, extra="forbid"): """ Configuration of the local bm25 models. """ k: Optional[float] = Field( default=1.2, description="Controls term frequency saturation. Higher values mean term frequency has more impact. Default is 1.2", ) b: Optional[float] = Field( default=0.75, description="Controls document length normalization. Ranges from 0 (no normalization) to 1 (full normalization). Higher values mean longer documents have less impact. Default is 0.75.", ) avg_len: Optional[float] = Field( default=256, description="Expected average document length in the collection. Default is 256." ) tokenizer: Optional["TokenizerType"] = Field(default=None, description="Configuration of the local bm25 models.") language: Optional[str] = Field( default=None, description="Defines which language to use for text preprocessing. This parameter is used to construct default stopwords filter and stemmer. To disable language-specific processing, set this to `'language': 'none'`. If not specified, English is assumed.", ) lowercase: Optional[bool] = Field( default=None, description="Lowercase the text before tokenization. Default is `true`." ) ascii_folding: Optional[bool] = Field( default=None, description="If true, normalize tokens by folding accented characters to ASCII (e.g., 'ação' -&gt; 'acao'). Default is `false`.", ) stopwords: Optional["StopwordsInterface"] = Field( default=None, description="Configuration of the stopwords filter. Supports list of pre-defined languages and custom stopwords. Default: initialized for specified `language` or English if not specified.", ) stemmer: Optional["StemmingAlgorithm"] = Field( default=None, description="Configuration of the stemmer. Processes tokens to their root form. Default: initialized Snowball stemmer for specified `language` or English if not specified.", ) min_token_len: Optional[int] = Field( default=None, description="Minimum token length to keep. If token is shorter than this, it will be discarded. Default is `None`, which means no minimum length.", ) max_token_len: Optional[int] = Field( default=None, description="Maximum token length to keep. If token is longer than this, it will be discarded. Default is `None`, which means no maximum length.", )
Bm25Config
python
ansible__ansible
test/units/parsing/vault/test_vault.py
{ "start": 17654, "end": 20705 }
class ____(unittest.TestCase): def test_binary_file_handle_not_encrypted(self): b_data = b"foobar" b_data_fo = io.BytesIO(b_data) self.assertFalse(vault.is_encrypted_file(b_data_fo)) def test_text_file_handle_not_encrypted(self): data = u"foobar" data_fo = io.StringIO(data) self.assertFalse(vault.is_encrypted_file(data_fo)) def test_binary_file_handle_encrypted(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible") b_data_fo = io.BytesIO(b_data) self.assertTrue(vault.is_encrypted_file(b_data_fo)) def test_text_file_handle_encrypted(self): data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % to_text(hexlify(b"ansible")) data_fo = io.StringIO(data) self.assertTrue(vault.is_encrypted_file(data_fo)) def test_binary_file_handle_invalid(self): data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " b_data = to_bytes(data) b_data_fo = io.BytesIO(b_data) self.assertFalse(vault.is_encrypted_file(b_data_fo, count=-1)) def test_text_file_handle_invalid(self): data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " data_fo = io.StringIO(data) self.assertFalse(vault.is_encrypted_file(data_fo, count=-1)) def test_file_already_read_from_finds_header(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") b_data_fo = io.BytesIO(b_data) b_data_fo.read(42) # Arbitrary number self.assertTrue(vault.is_encrypted_file(b_data_fo)) def test_file_already_read_from_saves_file_pos(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") b_data_fo = io.BytesIO(b_data) b_data_fo.read(69) # Arbitrary number vault.is_encrypted_file(b_data_fo) self.assertEqual(b_data_fo.tell(), 69) def test_file_with_offset(self): b_data = b"JUNK$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") b_data_fo = io.BytesIO(b_data) self.assertTrue(vault.is_encrypted_file(b_data_fo, start_pos=4)) def test_file_with_count(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") vault_length = len(b_data) b_data = b_data + u'ァ ア'.encode('utf-8') b_data_fo = io.BytesIO(b_data) self.assertTrue(vault.is_encrypted_file(b_data_fo, count=vault_length)) def test_file_with_offset_and_count(self): b_data = b"$ANSIBLE_VAULT;9.9;TEST\n%s" % hexlify(b"ansible\ntesting\nfile pos") vault_length = len(b_data) b_data = b'JUNK' + b_data + u'ァ ア'.encode('utf-8') b_data_fo = io.BytesIO(b_data) self.assertTrue(vault.is_encrypted_file(b_data_fo, start_pos=4, count=vault_length)) @pytest.mark.skipif(not vault.HAS_CRYPTOGRAPHY, reason="Skipping cryptography tests because cryptography is not installed")
TestVaultIsEncryptedFile
python
walkccc__LeetCode
solutions/421. Maximum XOR of Two Numbers in an Array/421.py
{ "start": 0, "end": 1074 }
class ____: def findMaximumXOR(self, nums: list[int]) -> int: maxNum = max(nums) if maxNum == 0: return 0 maxBit = int(math.log2(maxNum)) ans = 0 prefixMask = 0 # `prefixMask` grows like: 10000 -> 11000 -> ... -> 11111. # If ans is 11100 when i = 2, it means that before we reach the last two # bits, 11100 is the maximum XOR we have, and we're going to explore if we # can get another two 1s and put them into `ans`. for i in range(maxBit, -1, -1): prefixMask |= 1 << i # We only care about the left parts, # If i = 2, nums = [1110, 1011, 0111] # -> prefixes = [1100, 1000, 0100] prefixes = set([num & prefixMask for num in nums]) # If i = 1 and before this iteration, the ans is 10100, it means that we # want to grow the ans to 10100 | 1 << 1 = 10110 and we're looking for # XOR of two prefixes = candidate. candidate = ans | 1 << i for prefix in prefixes: if prefix ^ candidate in prefixes: ans = candidate break return ans
Solution
python
nedbat__coveragepy
tests/test_core.py
{ "start": 459, "end": 5950 }
class ____(CoverageTest): """Test that cores are chosen correctly.""" # This doesn't test failure modes, only successful requests. try: from coverage.tracer import CTracer has_ctracer = True except ImportError: has_ctracer = False def setUp(self) -> None: super().setUp() # Clean out the environment variable the test suite uses to control the # core it cares about. self.del_environ("COVERAGE_CORE") self.make_file("numbers.py", "print(123, 456)") def test_core_default(self) -> None: out = self.run_command("coverage run --debug=sys numbers.py") assert out.endswith("123 456\n") core = re_line(r" core:", out).strip() warns = re_lines(r"\(no-ctracer\)", out) if env.SYSMON_DEFAULT: assert core == "core: SysMonitor" assert not warns elif self.has_ctracer: assert core == "core: CTracer" assert not warns else: assert core == "core: PyTracer" assert bool(warns) == env.CPYTHON @pytest.mark.skipif(not has_ctracer, reason="No CTracer to request") def test_core_request_ctrace(self) -> None: self.set_environ("COVERAGE_CORE", "ctrace") out = self.run_command("coverage run --debug=sys numbers.py") assert out.endswith("123 456\n") core = re_line(r" core:", out).strip() assert core == "core: CTracer" @pytest.mark.skipif(has_ctracer, reason="CTracer needs to be missing") def test_core_request_ctrace_but_missing(self) -> None: self.make_file(".coveragerc", "[run]\ncore = ctrace\n") out = self.run_command("coverage run --debug=sys,pybehave numbers.py") assert out.endswith("123 456\n") core = re_line(r" core:", out).strip() assert core == "core: PyTracer" warns = re_lines(r"\(no-ctracer\)", out) assert bool(warns) == env.SHIPPING_WHEELS def test_core_request_pytrace(self) -> None: self.set_environ("COVERAGE_CORE", "pytrace") out = self.run_command("coverage run --debug=sys numbers.py") assert out.endswith("123 456\n") core = re_line(r" core:", out).strip() assert core == "core: PyTracer" @pytest.mark.skipif( env.METACOV and env.PYBEHAVIOR.pep669 and not testenv.CAN_MEASURE_BRANCHES, reason="12/13 can't do branches with sysmon, so metacov is too complicated", ) def test_core_request_sysmon(self) -> None: self.set_environ("COVERAGE_CORE", "sysmon") out = self.run_command("coverage run --debug=sys numbers.py") assert out.endswith("123 456\n") core = re_line(r" core:", out).strip() warns = re_lines(r"\(no-sysmon\)", out) if env.PYBEHAVIOR.pep669: assert core == "core: SysMonitor" assert not warns else: assert core in ["core: CTracer", "core: PyTracer"] assert warns def test_core_request_sysmon_no_dyncontext(self) -> None: # Use config core= for this test just to be different. self.make_file( ".coveragerc", """\ [run] core = sysmon dynamic_context = test_function """, ) out = self.run_command("coverage run --debug=sys numbers.py") assert out.endswith("123 456\n") core = re_line(r" core:", out).strip() assert core in ["core: CTracer", "core: PyTracer"] warns = re_lines(r"\(no-sysmon\)", out) assert len(warns) == 1 if env.PYBEHAVIOR.pep669: assert ( "Can't use core=sysmon: it doesn't yet support dynamic contexts, using default core" in warns[0] ) else: assert "sys.monitoring isn't available in this version, using default core" in warns[0] def test_core_request_sysmon_no_branches(self) -> None: # Use config core= for this test just to be different. self.make_file( ".coveragerc", """\ [run] core = sysmon branch = True """, ) out = self.run_command("coverage run --debug=sys numbers.py") assert out.endswith("123 456\n") core = re_line(r" core:", out).strip() warns = re_lines(r"\(no-sysmon\)", out) if env.PYBEHAVIOR.branch_right_left: assert core == "core: SysMonitor" assert not warns else: assert core in ["core: CTracer", "core: PyTracer"] assert len(warns) == 1 if env.PYBEHAVIOR.pep669: assert ( "sys.monitoring can't measure branches in this version, using default core" in warns[0] ) else: assert ( "sys.monitoring isn't available in this version, using default core" in warns[0] ) def test_core_request_nosuchcore(self) -> None: # Test the coverage misconfigurations in-process with pytest. Running a # subprocess doesn't capture the metacov in the subprocess because # coverage is misconfigured. self.set_environ("COVERAGE_CORE", "nosuchcore") cov = coverage.Coverage() with pytest.raises(ConfigError, match=r"Unknown core value: 'nosuchcore'"): self.start_import_stop(cov, "numbers")
CoverageCoreTest
python
pennersr__django-allauth
allauth/idp/oidc/views.py
{ "start": 9885, "end": 11027 }
class ____(View): def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: orequest = extract_params(request) try: headers, data, status = ( get_device_server().create_device_authorization_response(*orequest) ) if status == HTTPStatus.OK: client_id = request.POST["client_id"] scope: Optional[List[str]] = None if "scope" in request.POST: scope = request.POST["scope"].split() client = Client.objects.get(id=client_id) if not set(scope).issubset(set(client.get_scopes())): raise InvalidScopeError() device_codes.create(client_id, scope, data) except OAuth2Error as e: return HttpResponse( e.json, content_type="application/json", status=e.status_code ) return convert_response(headers, data, status) device_code = DeviceCodeView.as_view() @method_decorator(csrf_exempt, name="dispatch") @method_decorator(login_required, name="dispatch")
DeviceCodeView
python
pytorch__pytorch
torch/nn/modules/conv.py
{ "start": 60832, "end": 63710 }
class ____(_LazyConvXdMixin, Conv1d): # type: ignore[misc] r"""A :class:`torch.nn.Conv1d` module with lazy initialization of the ``in_channels`` argument. The ``in_channels`` argument of the :class:`Conv1d` is inferred from the ``input.size(1)``. The attributes that will be lazily initialized are `weight` and `bias`. Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation on lazy modules and their limitations. Args: out_channels (int): Number of channels produced by the convolution kernel_size (int or tuple): Size of the convolving kernel stride (int or tuple, optional): Stride of the convolution. Default: 1 padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0 dilation (int or tuple, optional): Spacing between kernel elements. Default: 1 groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True`` padding_mode (str, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'zeros'`` .. seealso:: :class:`torch.nn.Conv1d` and :class:`torch.nn.modules.lazy.LazyModuleMixin` """ # super class define this variable as None. "type: ignore[..] is required # since we are redefining the variable. cls_to_become = Conv1d # type: ignore[assignment] def __init__( self, out_channels: int, kernel_size: _size_1_t, stride: _size_1_t = 1, padding: _size_1_t = 0, dilation: _size_1_t = 1, groups: int = 1, bias: bool = True, padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros", device=None, dtype=None, ) -> None: factory_kwargs = {"device": device, "dtype": dtype} # pyrefly: ignore [bad-argument-type] super().__init__( 0, 0, kernel_size, stride, padding, dilation, groups, # bias is hardcoded to False to avoid creating tensor # that will soon be overwritten. False, padding_mode, **factory_kwargs, ) # pyrefly: ignore [bad-override, bad-argument-type] self.weight = UninitializedParameter(**factory_kwargs) self.out_channels = out_channels if bias: # pyrefly: ignore [bad-override, bad-argument-type] self.bias = UninitializedParameter(**factory_kwargs) def _get_num_spatial_dims(self) -> int: return 1 # LazyConv2d defines weight as a Tensor but derived class defines it as UninitializeParameter
LazyConv1d
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/streams.py
{ "start": 16932, "end": 17027 }
class ____(IterableExportEventsStreamAdjustableRange): data_field = "webPushSend"
WebPushSend
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_points05.py
{ "start": 315, "end": 1666 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_points05.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with point formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "line"}) chart.axis_ids = [45471616, 46804992] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$B$1:$B$5", "marker": {"type": "automatic"}, "points": [{"fill": {"color": "red"}}], } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", "marker": {"type": "automatic"}, } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
kubernetes-client__python
kubernetes/client/models/v1alpha3_device_taint_rule.py
{ "start": 383, "end": 6941 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'api_version': 'str', 'kind': 'str', 'metadata': 'V1ObjectMeta', 'spec': 'V1alpha3DeviceTaintRuleSpec' } attribute_map = { 'api_version': 'apiVersion', 'kind': 'kind', 'metadata': 'metadata', 'spec': 'spec' } def __init__(self, api_version=None, kind=None, metadata=None, spec=None, local_vars_configuration=None): # noqa: E501 """V1alpha3DeviceTaintRule - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._api_version = None self._kind = None self._metadata = None self._spec = None self.discriminator = None if api_version is not None: self.api_version = api_version if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata self.spec = spec @property def api_version(self): """Gets the api_version of this V1alpha3DeviceTaintRule. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1alpha3DeviceTaintRule. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1alpha3DeviceTaintRule. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1alpha3DeviceTaintRule. # noqa: E501 :type: str """ self._api_version = api_version @property def kind(self): """Gets the kind of this V1alpha3DeviceTaintRule. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1alpha3DeviceTaintRule. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1alpha3DeviceTaintRule. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1alpha3DeviceTaintRule. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1alpha3DeviceTaintRule. # noqa: E501 :return: The metadata of this V1alpha3DeviceTaintRule. # noqa: E501 :rtype: V1ObjectMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1alpha3DeviceTaintRule. :param metadata: The metadata of this V1alpha3DeviceTaintRule. # noqa: E501 :type: V1ObjectMeta """ self._metadata = metadata @property def spec(self): """Gets the spec of this V1alpha3DeviceTaintRule. # noqa: E501 :return: The spec of this V1alpha3DeviceTaintRule. # noqa: E501 :rtype: V1alpha3DeviceTaintRuleSpec """ return self._spec @spec.setter def spec(self, spec): """Sets the spec of this V1alpha3DeviceTaintRule. :param spec: The spec of this V1alpha3DeviceTaintRule. # noqa: E501 :type: V1alpha3DeviceTaintRuleSpec """ if self.local_vars_configuration.client_side_validation and spec is None: # noqa: E501 raise ValueError("Invalid value for `spec`, must not be `None`") # noqa: E501 self._spec = spec def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1alpha3DeviceTaintRule): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1alpha3DeviceTaintRule): return True return self.to_dict() != other.to_dict()
V1alpha3DeviceTaintRule
python
huggingface__transformers
tests/models/qwen3_vl/test_modeling_qwen3_vl.py
{ "start": 1175, "end": 6196 }
class ____: def __init__( self, parent, batch_size=3, seq_length=7, num_channels=3, ignore_index=-100, image_size=16, text_config={ "bos_token_id": 0, "eos_token_id": 1, "pad_token_id": 2, "hidden_act": "silu", "head_dim": 8, "hidden_size": 32, "vocab_size": 99, "intermediate_size": 37, "max_position_embeddings": 512, "model_type": "qwen3_vl", "num_attention_heads": 4, "num_hidden_layers": 2, "num_key_value_heads": 2, "rope_theta": 10000, "tie_word_embeddings": True, "rope_parameters": {"rope_type": "default", "mrope_section": [16, 8, 8], "mrope_interleaved": True}, }, vision_config={ "depth": 2, "in_chans": 3, "hidden_act": "gelu_pytorch_tanh", "intermediate_size": 32, "out_hidden_size": 32, "hidden_size": 32, "num_heads": 4, "patch_size": 16, "spatial_merge_size": 1, "temporal_patch_size": 2, "num_position_embeddings": 16, "deepstack_visual_indexes": [0, 1], }, image_token_id=3, video_token_id=4, vision_start_token_id=5, vision_end_token_id=6, tie_word_embeddings=True, is_training=True, ): self.parent = parent self.ignore_index = ignore_index self.is_training = is_training self.vision_config = vision_config self.text_config = text_config self.vocab_size = text_config["vocab_size"] self.bos_token_id = text_config["bos_token_id"] self.eos_token_id = text_config["eos_token_id"] self.pad_token_id = text_config["pad_token_id"] self.head_dim = text_config["head_dim"] self.hidden_size = text_config["hidden_size"] self.intermediate_size = text_config["intermediate_size"] self.num_hidden_layers = text_config["num_hidden_layers"] self.num_attention_heads = text_config["num_attention_heads"] self.num_key_value_heads = text_config["num_key_value_heads"] self.rope_theta = text_config["rope_theta"] self.rope_parameters = text_config["rope_parameters"] self.hidden_act = text_config["hidden_act"] self.max_position_embeddings = text_config["max_position_embeddings"] self.model_type = text_config["model_type"] self.vision_start_token_id = vision_start_token_id self.vision_end_token_id = vision_end_token_id self.image_token_id = image_token_id self.video_token_id = video_token_id self.tie_word_embeddings = tie_word_embeddings self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.num_image_tokens = 32 self.seq_length = seq_length + self.num_image_tokens def get_config(self): return Qwen3VLConfig( text_config=self.text_config, vision_config=self.vision_config, image_token_id=self.image_token_id, video_token_id=self.video_token_id, vision_start_token_id=self.vision_start_token_id, vision_end_token_id=self.vision_end_token_id, tie_word_embeddings=self.tie_word_embeddings, ) def prepare_config_and_inputs(self): config = self.get_config() patch_size = config.vision_config.patch_size temporal_patch_size = config.vision_config.temporal_patch_size pixel_values = floats_tensor( [ self.batch_size * (self.image_size**2) // (patch_size**2), self.num_channels * (patch_size**2) * temporal_patch_size, ] ) return config, pixel_values def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values = config_and_inputs input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) input_ids[:, -1] = self.pad_token_id input_ids[input_ids == self.video_token_id] = self.pad_token_id input_ids[input_ids == self.image_token_id] = self.pad_token_id input_ids[input_ids == self.vision_start_token_id] = self.pad_token_id input_ids[:, self.num_image_tokens] = self.image_token_id input_ids[:, self.num_image_tokens - 1] = self.vision_start_token_id inputs_dict = { "pixel_values": pixel_values, "image_grid_thw": torch.tensor([[1, 1, 1]] * self.batch_size, device=torch_device), "input_ids": input_ids, "attention_mask": attention_mask, } return config, inputs_dict @require_torch
Qwen3VLVisionText2TextModelTester
python
Farama-Foundation__Gymnasium
gymnasium/vector/vector_env.py
{ "start": 823, "end": 15169 }
class ____(Generic[ObsType, ActType, ArrayType]): """Base class for vectorized environments to run multiple independent copies of the same environment in parallel. Vector environments can provide a linear speed-up in the steps taken per second through sampling multiple sub-environments at the same time. Gymnasium contains two generalised Vector environments: :class:`AsyncVectorEnv` and :class:`SyncVectorEnv` along with several custom vector environment implementations. For :func:`reset` and :func:`step` batches `observations`, `rewards`, `terminations`, `truncations` and `info` for each sub-environment, see the example below. For the `rewards`, `terminations`, and `truncations`, the data is packaged into a NumPy array of shape `(num_envs,)`. For `observations` (and `actions`, the batching process is dependent on the type of observation (and action) space, and generally optimised for neural network input/outputs. For `info`, the data is kept as a dictionary such that a key will give the data for all sub-environment. For creating environments, :func:`make_vec` is a vector environment equivalent to :func:`make` for easily creating vector environments that contains several unique arguments for modifying environment qualities, number of environment, vectorizer type, vectorizer arguments. To avoid having to wait for all sub-environments to terminated before resetting, implementations can autoreset sub-environments on episode end (`terminated or truncated is True`). This is crucial for correct implementing training algorithms with vector environments. By default, Gymnasium's implementation uses `next-step` autoreset, with :class:`AutoresetMode` enum as the options. The mode used by vector environment should be available in `metadata["autoreset_mode"]`. Warning, some vector implementations or training algorithms will only support particular autoreset modes. For more information, read https://farama.org/Vector-Autoreset-Mode. Note: The info parameter of :meth:`reset` and :meth:`step` was originally implemented before v0.25 as a list of dictionary for each sub-environment. However, this was modified in v0.25+ to be a dictionary with a NumPy array for each key. To use the old info style, utilise the :class:`DictInfoToList` wrapper. Examples: >>> import gymnasium as gym >>> envs = gym.make_vec("CartPole-v1", num_envs=3, vectorization_mode="sync", wrappers=(gym.wrappers.TimeAwareObservation,)) >>> envs = gym.wrappers.vector.ClipReward(envs, min_reward=0.2, max_reward=0.8) >>> envs <ClipReward, SyncVectorEnv(CartPole-v1, num_envs=3)> >>> envs.num_envs 3 >>> envs.action_space MultiDiscrete([2 2 2]) >>> envs.observation_space Box([[-4.80000019 -inf -0.41887903 -inf 0. ] [-4.80000019 -inf -0.41887903 -inf 0. ] [-4.80000019 -inf -0.41887903 -inf 0. ]], [[4.80000019e+00 inf 4.18879032e-01 inf 5.00000000e+02] [4.80000019e+00 inf 4.18879032e-01 inf 5.00000000e+02] [4.80000019e+00 inf 4.18879032e-01 inf 5.00000000e+02]], (3, 5), float64) >>> observations, infos = envs.reset(seed=123) >>> observations array([[ 0.01823519, -0.0446179 , -0.02796401, -0.03156282, 0. ], [ 0.02852531, 0.02858594, 0.0469136 , 0.02480598, 0. ], [ 0.03517495, -0.000635 , -0.01098382, -0.03203924, 0. ]]) >>> infos {} >>> _ = envs.action_space.seed(123) >>> actions = envs.action_space.sample() >>> observations, rewards, terminations, truncations, infos = envs.step(actions) >>> observations array([[ 0.01734283, 0.15089367, -0.02859527, -0.33293587, 1. ], [ 0.02909703, -0.16717631, 0.04740972, 0.3319138 , 1. ], [ 0.03516225, -0.19559774, -0.01162461, 0.25715804, 1. ]]) >>> rewards array([0.8, 0.8, 0.8]) >>> terminations array([False, False, False]) >>> truncations array([False, False, False]) >>> infos {} >>> envs.close() The Vector Environments have the additional attributes for users to understand the implementation - :attr:`num_envs` - The number of sub-environment in the vector environment - :attr:`observation_space` - The batched observation space of the vector environment - :attr:`single_observation_space` - The observation space of a single sub-environment - :attr:`action_space` - The batched action space of the vector environment - :attr:`single_action_space` - The action space of a single sub-environment """ metadata: dict[str, Any] = {} spec: EnvSpec | None = None render_mode: str | None = None closed: bool = False observation_space: gym.Space action_space: gym.Space single_observation_space: gym.Space single_action_space: gym.Space num_envs: int _np_random: np.random.Generator | None = None _np_random_seed: int | None = None def reset( self, *, seed: int | None = None, options: dict[str, Any] | None = None, ) -> tuple[ObsType, dict[str, Any]]: # type: ignore """Reset all parallel environments and return a batch of initial observations and info. Args: seed: The environment reset seed options: If to return the options Returns: A batch of observations and info from the vectorized environment. Example: >>> import gymnasium as gym >>> envs = gym.make_vec("CartPole-v1", num_envs=3, vectorization_mode="sync") >>> observations, infos = envs.reset(seed=42) >>> observations array([[ 0.0273956 , -0.00611216, 0.03585979, 0.0197368 ], [ 0.01522993, -0.04562247, -0.04799704, 0.03392126], [-0.03774345, -0.02418869, -0.00942293, 0.0469184 ]], dtype=float32) >>> infos {} """ if seed is not None: self._np_random, self._np_random_seed = seeding.np_random(seed) def step( self, actions: ActType ) -> tuple[ObsType, ArrayType, ArrayType, ArrayType, dict[str, Any]]: """Take an action for each parallel environment. Args: actions: Batch of actions with the :attr:`action_space` shape. Returns: Batch of (observations, rewards, terminations, truncations, infos) Note: As the vector environments autoreset for a terminating and truncating sub-environments, this will occur on the next step after `terminated or truncated is True`. Example: >>> import gymnasium as gym >>> import numpy as np >>> envs = gym.make_vec("CartPole-v1", num_envs=3, vectorization_mode="sync") >>> _ = envs.reset(seed=42) >>> actions = np.array([1, 0, 1], dtype=np.int32) >>> observations, rewards, terminations, truncations, infos = envs.step(actions) >>> observations array([[ 0.02727336, 0.18847767, 0.03625453, -0.26141977], [ 0.01431748, -0.24002443, -0.04731862, 0.3110827 ], [-0.03822722, 0.1710671 , -0.00848456, -0.2487226 ]], dtype=float32) >>> rewards array([1., 1., 1.]) >>> terminations array([False, False, False]) >>> terminations array([False, False, False]) >>> infos {} """ raise NotImplementedError(f"{self.__str__()} step function is not implemented.") def render(self) -> tuple[RenderFrame, ...] | None: """Returns the rendered frames from the parallel environments. Returns: A tuple of rendered frames from the parallel environments """ raise NotImplementedError( f"{self.__str__()} render function is not implemented." ) def close(self, **kwargs: Any): """Close all parallel environments and release resources. It also closes all the existing image viewers, then calls :meth:`close_extras` and set :attr:`closed` as ``True``. Warnings: This function itself does not close the environments, it should be handled in :meth:`close_extras`. This is generic for both synchronous and asynchronous vectorized environments. Note: This will be automatically called when garbage collected or program exited. Args: **kwargs: Keyword arguments passed to :meth:`close_extras` """ if self.closed: return self.close_extras(**kwargs) self.closed = True def close_extras(self, **kwargs: Any): """Clean up the extra resources e.g. beyond what's in this base class.""" pass @property def np_random(self) -> np.random.Generator: """Returns the environment's internal :attr:`_np_random` that if not set will initialise with a random seed. Returns: Instances of `np.random.Generator` """ if self._np_random is None: self._np_random, self._np_random_seed = seeding.np_random() return self._np_random @np_random.setter def np_random(self, value: np.random.Generator): self._np_random = value self._np_random_seed = -1 @property def np_random_seed(self) -> int | None: """Returns the environment's internal :attr:`_np_random_seed` that if not set will first initialise with a random int as seed. If :attr:`np_random_seed` was set directly instead of through :meth:`reset` or :meth:`set_np_random_through_seed`, the seed will take the value -1. Returns: int: the seed of the current `np_random` or -1, if the seed of the rng is unknown """ if self._np_random_seed is None: self._np_random, self._np_random_seed = seeding.np_random() return self._np_random_seed @property def unwrapped(self): """Return the base environment.""" return self def _add_info( self, vector_infos: dict[str, Any], env_info: dict[str, Any], env_num: int ) -> dict[str, Any]: """Add env info to the info dictionary of the vectorized environment. Given the `info` of a single environment add it to the `infos` dictionary which represents all the infos of the vectorized environment. Every `key` of `info` is paired with a boolean mask `_key` representing whether or not the i-indexed environment has this `info`. Args: vector_infos (dict): the infos of the vectorized environment env_info (dict): the info coming from the single environment env_num (int): the index of the single environment Returns: infos (dict): the (updated) infos of the vectorized environment """ for key, value in env_info.items(): # It is easier for users to access their `final_obs` in the unbatched array of `obs` objects if key == "final_obs": if "final_obs" in vector_infos: array = vector_infos["final_obs"] else: array = np.full(self.num_envs, fill_value=None, dtype=object) array[env_num] = value # If value is a dictionary, then we apply the `_add_info` recursively. elif isinstance(value, dict): array = self._add_info(vector_infos.get(key, {}), value, env_num) # Otherwise, we are a base case to group the data else: # If the key doesn't exist in the vector infos, then we can create an array of that batch type if key not in vector_infos: if type(value) in [int, float, bool] or issubclass( type(value), np.number ): array = np.zeros(self.num_envs, dtype=type(value)) elif isinstance(value, np.ndarray): # We assume that all instances of the np.array info are of the same shape array = np.zeros( (self.num_envs, *value.shape), dtype=value.dtype ) else: # For unknown objects, we use a Numpy object array array = np.full(self.num_envs, fill_value=None, dtype=object) # Otherwise, just use the array that already exists else: array = vector_infos[key] # Assign the data in the `env_num` position # We only want to run this for the base-case data (not recursive data forcing the ugly function structure) array[env_num] = value # Get the array mask and if it doesn't already exist then create a zero bool array array_mask = vector_infos.get( f"_{key}", np.zeros(self.num_envs, dtype=np.bool_) ) array_mask[env_num] = True # Update the vector info with the updated data and mask information vector_infos[key], vector_infos[f"_{key}"] = array, array_mask return vector_infos def __del__(self): """Closes the vector environment.""" if not getattr(self, "closed", True): self.close() def __repr__(self) -> str: """Returns a string representation of the vector environment. Returns: A string containing the class name, number of environments and environment spec id """ if self.spec is None: return f"{self.__class__.__name__}(num_envs={self.num_envs})" else: return ( f"{self.__class__.__name__}({self.spec.id}, num_envs={self.num_envs})" )
VectorEnv
python
pandas-dev__pandas
pandas/errors/__init__.py
{ "start": 19883, "end": 20972 }
class ____(Exception): """ Exception raised by ``agg`` when the functions are ill-specified. The exception raised in two scenarios. The first way is calling ``agg`` on a Dataframe or Series using a nested renamer (dict-of-dict). The second way is calling ``agg`` on a Dataframe with duplicated functions names without assigning column name. See Also -------- DataFrame.agg : Aggregate using one or more operations over the specified axis. Series.agg : Aggregate using one or more operations over the specified axis. Examples -------- >>> df = pd.DataFrame({"A": [1, 1, 1, 2, 2], "B": range(5), "C": range(5)}) >>> df.groupby("A").B.agg({"foo": "count"}) # doctest: +SKIP ... # SpecificationError: nested renamer is not supported >>> df.groupby("A").agg({"B": {"foo": ["sum", "max"]}}) # doctest: +SKIP ... # SpecificationError: nested renamer is not supported >>> df.groupby("A").agg(["min", "min"]) # doctest: +SKIP ... # SpecificationError: nested renamer is not supported """
SpecificationError
python
optuna__optuna
optuna/cli.py
{ "start": 21349, "end": 22585 }
class ____(_BaseCommand): """Upgrade the schema of an RDB storage.""" def take_action(self, parsed_args: Namespace) -> int: storage_url = _check_storage_url(parsed_args.storage) try: storage = RDBStorage( storage_url, skip_compatibility_check=True, skip_table_creation=True ) except sqlalchemy.exc.ArgumentError: self.logger.error("Invalid RDBStorage URL.") return 1 current_version = storage.get_current_version() head_version = storage.get_head_version() known_versions = storage.get_all_versions() if current_version == head_version: self.logger.info("This storage is up-to-date.") elif current_version in known_versions: self.logger.info("Upgrading the storage schema to the latest version.") storage.upgrade() self.logger.info("Completed to upgrade the storage.") else: optuna_warn( "Your optuna version seems outdated against the storage version. " "Please try updating optuna to the latest version by " "`$ pip install -U optuna`." ) return 0
_StorageUpgrade
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_public_packages.py
{ "start": 382, "end": 11131 }
class ____: """Test suite for public package discovery functions.""" def test_get_public_dagster_packages_with_real_repo(self): """Test getting public packages from the real Dagster repository.""" packages = get_public_dagster_packages() # Should have at least the core dagster package assert len(packages) > 0 # Should include dagster core dagster_core = next((p for p in packages if p.name == "dagster"), None) assert dagster_core is not None assert dagster_core.module_name == "dagster" assert dagster_core.directory_name == "dagster" # Should include dagster-pipes dagster_pipes = next((p for p in packages if p.name == "dagster-pipes"), None) assert dagster_pipes is not None assert dagster_pipes.module_name == "dagster_pipes" assert dagster_pipes.directory_name == "dagster-pipes" # Should include libraries from the libraries/ directory (the repo should have many) library_packages = [p for p in packages if p.name not in ["dagster", "dagster-pipes"]] assert len(library_packages) > 10 # Should have many library packages # All library packages should start with "dagster-" for lib in library_packages: assert lib.name.startswith("dagster-") assert lib.module_name == lib.name.replace("-", "_") # All packages should have proper module name conversion for pkg in packages: assert pkg.module_name == pkg.name.replace("-", "_") # Packages should be sorted by name package_names = [p.name for p in packages] assert package_names == sorted(package_names) # All packages should have valid paths that exist for pkg in packages: assert pkg.path.exists() assert pkg.path.is_dir() def test_get_public_dagster_packages_with_mock_structure(self): """Test getting public packages from a mock directory structure.""" with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Create mock directory structure python_modules_dir = temp_path / "python_modules" python_modules_dir.mkdir() # Create dagster core package dagster_dir = python_modules_dir / "dagster" dagster_dir.mkdir() (dagster_dir / "setup.py").write_text("# dagster setup") # Create dagster-pipes package pipes_dir = python_modules_dir / "dagster-pipes" pipes_dir.mkdir() (pipes_dir / "setup.py").write_text("# dagster-pipes setup") packages = get_public_dagster_packages(temp_path) assert len(packages) == 2 # dagster + dagster-pipes # Check dagster core dagster_pkg = next(p for p in packages if p.name == "dagster") assert dagster_pkg.module_name == "dagster" # Check dagster-pipes pipes_pkg = next(p for p in packages if p.name == "dagster-pipes") assert pipes_pkg.module_name == "dagster_pipes" # Check module name conversion for pkg in packages: assert pkg.module_name == pkg.name.replace("-", "_") def test_get_public_dagster_packages_missing_directory(self): """Test error handling when python_modules directory doesn't exist.""" with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) with pytest.raises(FileNotFoundError, match="python_modules directory not found"): get_public_dagster_packages(temp_path) def test_get_public_dagster_packages_no_core_package(self): """Test behavior when dagster core package is missing.""" with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Create python_modules but no dagster core python_modules_dir = temp_path / "python_modules" python_modules_dir.mkdir() # Create dagster-pipes but not dagster pipes_dir = python_modules_dir / "dagster-pipes" pipes_dir.mkdir() (pipes_dir / "setup.py").write_text("# dagster-pipes setup") packages = get_public_dagster_packages(temp_path) # Should only have the pipes package assert len(packages) == 1 assert packages[0].name == "dagster-pipes" def test_get_public_dagster_packages_only_core(self): """Test behavior when only dagster core package exists.""" with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Create python_modules with only dagster core python_modules_dir = temp_path / "python_modules" python_modules_dir.mkdir() dagster_dir = python_modules_dir / "dagster" dagster_dir.mkdir() (dagster_dir / "setup.py").write_text("# dagster setup") packages = get_public_dagster_packages(temp_path) # Should only have dagster core assert len(packages) == 1 assert packages[0].name == "dagster" def test_get_top_level_packages(self): """Test getting just top-level package names (dagster and dagster-pipes only).""" names = get_top_level_packages() assert "dagster" in names assert "dagster-pipes" in names assert all(isinstance(name, str) for name in names) # Should be sorted assert names == sorted(names) # Should only contain the two top-level packages assert len(names) == 2 assert set(names) == {"dagster", "dagster-pipes"} def test_get_top_level_modules(self): """Test getting just top-level module names (dagster and dagster_pipes only).""" module_names = get_top_level_modules() assert "dagster" in module_names assert "dagster_pipes" in module_names assert all(isinstance(name, str) for name in module_names) # Should be sorted assert module_names == sorted(module_names) # Should not contain dashes (converted to underscores) assert all("-" not in name for name in module_names) # Should only contain the two top-level modules assert len(module_names) == 2 assert set(module_names) == {"dagster", "dagster_pipes"} def test_get_public_package_names(self): """Test getting all public package names (top-level packages + libraries).""" names = get_public_package_names() # Should include top-level packages assert "dagster" in names assert "dagster-pipes" in names # Should include many libraries library_names = [name for name in names if name not in ["dagster", "dagster-pipes"]] assert len(library_names) > 10 # All library names should start with "dagster-" for lib_name in library_names: assert lib_name.startswith("dagster-") # Should be sorted assert names == sorted(names) def test_get_public_module_names(self): """Test getting all public module names (top-level packages + libraries).""" module_names = get_public_module_names() # Should include top-level modules assert "dagster" in module_names assert "dagster_pipes" in module_names # Should include many library modules library_modules = [ name for name in module_names if name not in ["dagster", "dagster_pipes"] ] assert len(library_modules) > 10 # All library modules should start with "dagster_" for lib_module in library_modules: assert lib_module.startswith("dagster_") # Should not contain dashes (converted to underscores) assert all("-" not in name for name in module_names) # Should be sorted assert module_names == sorted(module_names) def test_is_public_dagster_package(self): """Test checking if a package name is public.""" assert is_public_dagster_package("dagster") is True assert is_public_dagster_package("dagster-pipes") is True assert is_public_dagster_package("not-dagster") is False assert is_public_dagster_package("") is False def test_is_public_dagster_module(self): """Test checking if a module name is public.""" assert is_public_dagster_module("dagster") is True assert is_public_dagster_module("dagster_pipes") is True assert is_public_dagster_module("not_dagster") is False assert is_public_dagster_module("") is False def test_public_package_record(self): """Test the PublicPackage record structure.""" pkg = PublicPackage( name="dagster-test", directory_name="dagster-test", module_name="dagster_test", path=Path("/fake/path"), ) assert pkg.name == "dagster-test" assert pkg.directory_name == "dagster-test" assert pkg.module_name == "dagster_test" assert pkg.path == Path("/fake/path") # Test record immutability with pytest.raises(AttributeError): pkg.name = "changed" # type: ignore def test_package_name_to_module_name_conversion(self): """Test that package names are correctly converted to module names.""" packages = get_public_dagster_packages() for pkg in packages: assert pkg.module_name == pkg.name.replace("-", "_") if pkg.name != "dagster": assert pkg.name.startswith("dagster-") assert pkg.module_name.startswith("dagster_") def test_consistent_ordering(self): """Test that functions return consistent ordering across calls.""" packages1 = get_public_dagster_packages() packages2 = get_public_dagster_packages() assert [p.name for p in packages1] == [p.name for p in packages2] # Test top-level functions top_level_packages1 = get_top_level_packages() top_level_packages2 = get_top_level_packages() assert top_level_packages1 == top_level_packages2 top_level_modules1 = get_top_level_modules() top_level_modules2 = get_top_level_modules() assert top_level_modules1 == top_level_modules2 # Test all public functions public_names1 = get_public_package_names() public_names2 = get_public_package_names() assert public_names1 == public_names2 public_modules1 = get_public_module_names() public_modules2 = get_public_module_names() assert public_modules1 == public_modules2
TestPublicPackages
python
TheAlgorithms__Python
graphs/graph_adjacency_list.py
{ "start": 765, "end": 6886 }
class ____[T]: def __init__( self, vertices: list[T], edges: list[list[T]], directed: bool = True ) -> None: """ Parameters: - vertices: (list[T]) The list of vertex names the client wants to pass in. Default is empty. - edges: (list[list[T]]) The list of edges the client wants to pass in. Each edge is a 2-element list. Default is empty. - directed: (bool) Indicates if graph is directed or undirected. Default is True. """ self.adj_list: dict[T, list[T]] = {} # dictionary of lists of T self.directed = directed # Falsey checks edges = edges or [] vertices = vertices or [] for vertex in vertices: self.add_vertex(vertex) for edge in edges: if len(edge) != 2: msg = f"Invalid input: {edge} is the wrong length." raise ValueError(msg) self.add_edge(edge[0], edge[1]) def add_vertex(self, vertex: T) -> None: """ Adds a vertex to the graph. If the given vertex already exists, a ValueError will be thrown. >>> g = GraphAdjacencyList(vertices=[], edges=[], directed=False) >>> g.add_vertex("A") >>> g.adj_list {'A': []} >>> g.add_vertex("A") Traceback (most recent call last): ... ValueError: Incorrect input: A is already in the graph. """ if self.contains_vertex(vertex): msg = f"Incorrect input: {vertex} is already in the graph." raise ValueError(msg) self.adj_list[vertex] = [] def add_edge(self, source_vertex: T, destination_vertex: T) -> None: """ Creates an edge from source vertex to destination vertex. If any given vertex doesn't exist or the edge already exists, a ValueError will be thrown. """ if not ( self.contains_vertex(source_vertex) and self.contains_vertex(destination_vertex) ): msg = ( f"Incorrect input: Either {source_vertex} or " f"{destination_vertex} does not exist" ) raise ValueError(msg) if self.contains_edge(source_vertex, destination_vertex): msg = ( "Incorrect input: The edge already exists between " f"{source_vertex} and {destination_vertex}" ) raise ValueError(msg) # add the destination vertex to the list associated with the source vertex # and vice versa if not directed self.adj_list[source_vertex].append(destination_vertex) if not self.directed: self.adj_list[destination_vertex].append(source_vertex) def remove_vertex(self, vertex: T) -> None: """ Removes the given vertex from the graph and deletes all incoming and outgoing edges from the given vertex as well. If the given vertex does not exist, a ValueError will be thrown. """ if not self.contains_vertex(vertex): msg = f"Incorrect input: {vertex} does not exist in this graph." raise ValueError(msg) if not self.directed: # If not directed, find all neighboring vertices and delete all references # of edges connecting to the given vertex for neighbor in self.adj_list[vertex]: self.adj_list[neighbor].remove(vertex) else: # If directed, search all neighbors of all vertices and delete all # references of edges connecting to the given vertex for edge_list in self.adj_list.values(): if vertex in edge_list: edge_list.remove(vertex) # Finally, delete the given vertex and all of its outgoing edge references self.adj_list.pop(vertex) def remove_edge(self, source_vertex: T, destination_vertex: T) -> None: """ Removes the edge between the two vertices. If any given vertex doesn't exist or the edge does not exist, a ValueError will be thrown. """ if not ( self.contains_vertex(source_vertex) and self.contains_vertex(destination_vertex) ): msg = ( f"Incorrect input: Either {source_vertex} or " f"{destination_vertex} does not exist" ) raise ValueError(msg) if not self.contains_edge(source_vertex, destination_vertex): msg = ( "Incorrect input: The edge does NOT exist between " f"{source_vertex} and {destination_vertex}" ) raise ValueError(msg) # remove the destination vertex from the list associated with the source # vertex and vice versa if not directed self.adj_list[source_vertex].remove(destination_vertex) if not self.directed: self.adj_list[destination_vertex].remove(source_vertex) def contains_vertex(self, vertex: T) -> bool: """ Returns True if the graph contains the vertex, False otherwise. """ return vertex in self.adj_list def contains_edge(self, source_vertex: T, destination_vertex: T) -> bool: """ Returns True if the graph contains the edge from the source_vertex to the destination_vertex, False otherwise. If any given vertex doesn't exist, a ValueError will be thrown. """ if not ( self.contains_vertex(source_vertex) and self.contains_vertex(destination_vertex) ): msg = ( f"Incorrect input: Either {source_vertex} " f"or {destination_vertex} does not exist." ) raise ValueError(msg) return destination_vertex in self.adj_list[source_vertex] def clear_graph(self) -> None: """ Clears all vertices and edges. """ self.adj_list = {} def __repr__(self) -> str: return pformat(self.adj_list)
GraphAdjacencyList
python
pytorch__pytorch
torch/distributed/fsdp/_common_utils.py
{ "start": 3778, "end": 6514 }
class ____(_State): def __init__(self) -> None: # TODO: Move all the attributes to this class to enable typing for # FSDP/fully_shard. self._ignored_modules: set[nn.Module] = set() self._ignored_params: set[nn.Parameter] = set() # Buffer names are cleaned (without wrapper prefixes) self._ignored_buffer_names: set[str] = set() self.process_group: Optional[dist.ProcessGroup] = None self.rank: int = -1 self.world_size: int = -1 self._device_mesh: Optional[DeviceMesh] = None self.sharding_strategy = ShardingStrategy.FULL_SHARD self._use_orig_params: bool = False self.training_state = TrainingState.IDLE self._unshard_params_ctx: dict[nn.Module, Generator] = {} self._state_dict_type: StateDictType = StateDictType.FULL_STATE_DICT self._state_dict_config: StateDictConfig = FullStateDictConfig() self._optim_state_dict_config: OptimStateDictConfig = FullOptimStateDictConfig() self._is_root: Optional[bool] = None self._handle: Optional[flat_param_file.FlatParamHandle] = None self._fully_sharded_module_to_handle: dict[ nn.Module, Optional[flat_param_file.FlatParamHandle] ] = {} self.compute_device: Optional[torch.device] = None self._gradient_predivide_factor: int = 0 self._gradient_postdivide_factor: int = 0 self._comm_hook: Optional[Callable] = None self._comm_hook_state: Optional[Any] = None self._unshard_event: Optional[torch.Event] = None # Abstract device handle for fsdp compute device. For now, # the compute device must implement cuda semantics used by fsdp self._device_handle: _FSDPDeviceHandle = _UninitializedDeviceHandle() # All following attributes should only be used for root states: # Save these static lists to avoid the repeated tree traversals self._all_fsdp_states: list[_FSDPState] = [] self._all_handles: list[flat_param_file.FlatParamHandle] = [] self._fsdp_extension: Optional[FSDPExtensions] = None def _get_module_fsdp_state(module: nn.Module) -> Optional[_FSDPState]: state = _get_module_state(module) if state is None or not isinstance(state, _FSDPState): return None return state def _get_module_fsdp_state_if_fully_sharded_module( module: nn.Module, ) -> Optional[_FSDPState]: state = _get_module_fsdp_state(module) if state is None: return None if state == module: # FullyShardedDataParallel module case. return state if module in state._fully_sharded_module_to_handle: # fully_shard case. return state return None
_FSDPState
python
pytorch__pytorch
torch/_dynamo/exc.py
{ "start": 1939, "end": 2162 }
class ____(RuntimeError): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self._torch_dynamo_tracer_output: Optional[DynamoTracerOutput] = None
TorchDynamoException
python
google__pytype
pytype/overlays/attr_overlay.py
{ "start": 2021, "end": 2252 }
class ____(_AttrOverlayBase): """A custom overlay for the 'attrs' module. 'attrs' is the new namespace for the attrs library's next-generation APIs (attrs.define, attrs.field, etc.) """ _MODULE_NAME = "attrs"
AttrsOverlay
python
walkccc__LeetCode
solutions/155. Min Stack/155.py
{ "start": 0, "end": 342 }
class ____: def __init__(self): self.stack = [] def push(self, x: int) -> None: mn = x if not self.stack else min(self.stack[-1][1], x) self.stack.append([x, mn]) def pop(self) -> None: self.stack.pop() def top(self) -> int: return self.stack[-1][0] def getMin(self) -> int: return self.stack[-1][1]
MinStack
python
huggingface__transformers
src/transformers/models/switch_transformers/modeling_switch_transformers.py
{ "start": 48531, "end": 55522 }
class ____(SwitchTransformersPreTrainedModel, GenerationMixin): _tied_weights_keys = { "encoder.embed_tokens.weight": "shared.weight", "decoder.embed_tokens.weight": "shared.weight", "lm_head.weight": "shared.weight", } def __init__(self, config: SwitchTransformersConfig): super().__init__(config) self.model_dim = config.d_model self.shared = nn.Embedding(config.vocab_size, config.d_model) encoder_config = copy.deepcopy(config) encoder_config.is_decoder = False encoder_config.use_cache = False encoder_config.tie_encoder_decoder = False self.encoder = SwitchTransformersStack(encoder_config) decoder_config = copy.deepcopy(config) decoder_config.is_decoder = True decoder_config.tie_encoder_decoder = False decoder_config.num_layers = config.num_decoder_layers self.decoder = SwitchTransformersStack(decoder_config) self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False) self.router_z_loss_coef = config.router_z_loss_coef self.router_aux_loss_coef = config.router_aux_loss_coef self.post_init() def get_input_embeddings(self): return self.shared def set_input_embeddings(self, new_embeddings): self.shared = new_embeddings self.encoder.set_input_embeddings(new_embeddings) self.decoder.set_input_embeddings(new_embeddings) @auto_docstring @can_return_tuple def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.BoolTensor] = None, encoder_outputs: Optional[tuple[tuple[torch.Tensor]]] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, decoder_inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_router_logits: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.FloatTensor], Seq2SeqMoEOutput]: if encoder_outputs is None: encoder_outputs = self.encoder( input_ids=input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs ) hidden_states = encoder_outputs[0] if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None: # get decoder inputs from shifting lm labels to the right decoder_input_ids = self._shift_right(labels) # Decode decoder_outputs = self.decoder( input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, inputs_embeds=decoder_inputs_embeds, past_key_values=past_key_values, encoder_hidden_states=hidden_states, encoder_attention_mask=attention_mask, cache_position=cache_position, **kwargs, ) sequence_output = decoder_outputs.last_hidden_state if self.config.tie_word_embeddings: # Rescale output before projecting on vocab # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586 sequence_output = sequence_output * (self.model_dim**-0.5) lm_logits = self.lm_head(sequence_output) loss = None encoder_z_loss = None encoder_aux_loss = None decoder_z_loss = None decoder_aux_loss = None if output_router_logits: # Compute the router loss (z_loss + auxiliary loss) for each router in the encoder and decoder if self.encoder.config.encoder_sparse_step > 1: encoder_router_logits, encoder_expert_indexes = self._unpack_router_logits(encoder_outputs[-1]) encoder_z_loss = router_z_loss_func(encoder_router_logits) encoder_router_probs = nn.Softmax(dim=-1)(encoder_router_logits) encoder_aux_loss = load_balancing_loss_func(encoder_router_probs, encoder_expert_indexes) else: encoder_z_loss = 0 encoder_aux_loss = 0 if self.decoder.config.decoder_sparse_step > 1: decoder_router_logits, decoder_expert_indexes = self._unpack_router_logits(decoder_outputs[-1]) decoder_z_loss = router_z_loss_func(decoder_router_logits) decoder_router_probs = nn.Softmax(dim=-1)(decoder_router_logits) decoder_aux_loss = load_balancing_loss_func(decoder_router_probs, decoder_expert_indexes) else: decoder_z_loss = 0 decoder_aux_loss = 0 if labels is not None: loss_fct = CrossEntropyLoss(ignore_index=-100) # move labels to correct device to enable PP labels = labels.to(lm_logits.device) loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1)) if output_router_logits: z_loss = self.router_z_loss_coef * (encoder_z_loss + decoder_z_loss) aux_loss = self.router_aux_loss_coef * (encoder_aux_loss + decoder_aux_loss) loss = loss + z_loss + aux_loss return Seq2SeqMoEOutput( loss=loss, logits=lm_logits, encoder_z_loss=encoder_z_loss, encoder_aux_loss=encoder_aux_loss, decoder_z_loss=decoder_z_loss, decoder_aux_loss=decoder_aux_loss, past_key_values=decoder_outputs.past_key_values, decoder_hidden_states=decoder_outputs.hidden_states, decoder_attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions, decoder_router_logits=decoder_outputs.router_probs, encoder_last_hidden_state=encoder_outputs.last_hidden_state, encoder_hidden_states=encoder_outputs.hidden_states, encoder_attentions=encoder_outputs.attentions, encoder_router_logits=encoder_outputs.router_probs, ) def _unpack_router_logits(self, router_outputs): total_router_logits = [] total_expert_indexes = [] for router_output in router_outputs: if len(router_output[0].shape) > 1: router_logits, expert_indexes = router_output total_router_logits.append(router_logits) total_expert_indexes.append(expert_indexes) return torch.cat(total_router_logits, dim=1), torch.cat(total_expert_indexes, dim=1) def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor): return self._shift_right(labels)
SwitchTransformersForConditionalGeneration
python
wandb__wandb
wandb/sdk/artifacts/_generated/fragments.py
{ "start": 535, "end": 595 }
class ____(GQLResult): name: str
ProjectInfoFragmentEntity
python
django__django
django/db/backends/sqlite3/client.py
{ "start": 64, "end": 321 }
class ____(BaseDatabaseClient): executable_name = "sqlite3" @classmethod def settings_to_cmd_args_env(cls, settings_dict, parameters): args = [cls.executable_name, settings_dict["NAME"], *parameters] return args, None
DatabaseClient
python
ray-project__ray
python/ray/dashboard/modules/metrics/metrics_head.py
{ "start": 3009, "end": 16221 }
class ____(SubprocessModule): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grafana_host = os.environ.get(GRAFANA_HOST_ENV_VAR, DEFAULT_GRAFANA_HOST) self.prometheus_host = os.environ.get( PROMETHEUS_HOST_ENV_VAR, DEFAULT_PROMETHEUS_HOST ) default_metrics_root = os.path.join(self.session_dir, "metrics") self.prometheus_headers = parse_prom_headers( os.environ.get( PROMETHEUS_HEADERS_ENV_VAR, DEFAULT_PROMETHEUS_HEADERS, ) ) session_latest_metrics_root = os.path.join( self.temp_dir, SESSION_LATEST, "metrics" ) self._metrics_root = os.environ.get( METRICS_OUTPUT_ROOT_ENV_VAR, default_metrics_root ) self._metrics_root_session_latest = os.environ.get( METRICS_OUTPUT_ROOT_ENV_VAR, session_latest_metrics_root ) self._grafana_config_output_path = os.path.join(self._metrics_root, "grafana") self._grafana_session_latest_config_output_path = os.path.join( self._metrics_root_session_latest, "grafana" ) self._grafana_dashboard_output_dir = os.environ.get( GRAFANA_DASHBOARD_OUTPUT_DIR_ENV_VAR, os.path.join(self._grafana_config_output_path, "dashboards"), ) self._prometheus_name = os.environ.get( PROMETHEUS_NAME_ENV_VAR, DEFAULT_PROMETHEUS_NAME ) self._grafana_org_id = os.environ.get( GRAFANA_ORG_ID_ENV_VAR, DEFAULT_GRAFANA_ORG_ID ) self._grafana_cluster_filter = os.environ.get(GRAFANA_CLUSTER_FILTER_ENV_VAR) # To be set later when dashboards gets generated self._dashboard_uids = {} @routes.get("/api/grafana_health") async def grafana_health(self, req) -> aiohttp.web.Response: """ Endpoint that checks if Grafana is running """ # If disabled, we don't want to show the metrics tab at all. if self.grafana_host == GRAFANA_HOST_DISABLED_VALUE: return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.OK, message="Grafana disabled", grafana_host=GRAFANA_HOST_DISABLED_VALUE, ) grafana_iframe_host = os.environ.get( GRAFANA_IFRAME_HOST_ENV_VAR, self.grafana_host ) path = f"{self.grafana_host}/{GRAFANA_HEALTHCHECK_PATH}" try: async with self.http_session.get(path) as resp: if resp.status != 200: return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.INTERNAL_ERROR, message="Grafana healthcheck failed", status=resp.status, ) json = await resp.json() # Check if the required Grafana services are running. if json["database"] != "ok": return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.INTERNAL_ERROR, message="Grafana healthcheck failed. Database not ok.", status=resp.status, json=json, ) return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.OK, message="Grafana running", grafana_host=grafana_iframe_host, grafana_org_id=self._grafana_org_id, session_name=self.session_name, dashboard_uids=self._dashboard_uids, dashboard_datasource=self._prometheus_name, grafana_cluster_filter=self._grafana_cluster_filter, ) except Exception as e: logger.debug( "Error fetching grafana endpoint. Is grafana running?", exc_info=e ) return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.INTERNAL_ERROR, message="Grafana healthcheck failed", exception=str(e), ) @routes.get("/api/prometheus_health") async def prometheus_health(self, req): try: path = f"{self.prometheus_host}/{PROMETHEUS_HEALTHCHECK_PATH}" async with self.http_session.get( path, headers=self.prometheus_headers ) as resp: if resp.status != 200: return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.INTERNAL_ERROR, message="prometheus healthcheck failed.", status=resp.status, ) return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.OK, message="prometheus running", ) except Exception as e: logger.debug( "Error fetching prometheus endpoint. Is prometheus running?", exc_info=e ) return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.INTERNAL_ERROR, message="prometheus healthcheck failed.", reason=str(e), ) def _create_default_grafana_configs(self): """ Creates the Grafana configurations that are by default provided by Ray. """ # Create Grafana configuration folder if os.path.exists(self._grafana_config_output_path): shutil.rmtree(self._grafana_config_output_path) os.makedirs(self._grafana_config_output_path, exist_ok=True) # Overwrite Grafana's configuration file grafana_provisioning_folder = os.path.join( self._grafana_config_output_path, "provisioning" ) grafana_prov_folder_with_latest_session = os.path.join( self._grafana_session_latest_config_output_path, "provisioning" ) with open( os.path.join( self._grafana_config_output_path, "grafana.ini", ), "w", ) as f: f.write( GRAFANA_INI_TEMPLATE.format( grafana_provisioning_folder=grafana_prov_folder_with_latest_session ) ) # Overwrite Grafana's dashboard provisioning directory based on env var dashboard_provisioning_path = os.path.join( grafana_provisioning_folder, "dashboards" ) os.makedirs( dashboard_provisioning_path, exist_ok=True, ) with open( os.path.join( dashboard_provisioning_path, "default.yml", ), "w", ) as f: f.write( DASHBOARD_PROVISIONING_TEMPLATE.format( dashboard_output_folder=self._grafana_dashboard_output_dir ) ) # Overwrite Grafana's Prometheus datasource based on env var prometheus_host = os.environ.get( PROMETHEUS_HOST_ENV_VAR, DEFAULT_PROMETHEUS_HOST ) prometheus_headers = parse_prom_headers( os.environ.get(PROMETHEUS_HEADERS_ENV_VAR, DEFAULT_PROMETHEUS_HEADERS) ) # parse_prom_headers will make sure the prometheus_headers is either format of: # 1. {"H1": "V1", "H2": "V2"} or # 2. [["H1", "V1"], ["H2", "V2"], ["H2", "V3"]] prometheus_header_pairs = [] if isinstance(prometheus_headers, list): prometheus_header_pairs = prometheus_headers elif isinstance(prometheus_headers, dict): prometheus_header_pairs = list(prometheus_headers.items()) data_sources_path = os.path.join(grafana_provisioning_folder, "datasources") os.makedirs( data_sources_path, exist_ok=True, ) os.makedirs( self._grafana_dashboard_output_dir, exist_ok=True, ) with open( os.path.join( data_sources_path, "default.yml", ), "w", ) as f: f.write( GRAFANA_DATASOURCE_TEMPLATE( prometheus_host=prometheus_host, prometheus_name=self._prometheus_name, jsonData={ f"httpHeaderName{i+1}": header for i, (header, _) in enumerate(prometheus_header_pairs) }, secureJsonData={ f"httpHeaderValue{i+1}": value for i, (_, value) in enumerate(prometheus_header_pairs) }, ) ) with open( os.path.join( self._grafana_dashboard_output_dir, "default_grafana_dashboard.json", ), "w", ) as f: ( content, self._dashboard_uids["default"], ) = generate_default_grafana_dashboard() f.write(content) with open( os.path.join( self._grafana_dashboard_output_dir, "serve_grafana_dashboard.json", ), "w", ) as f: content, self._dashboard_uids["serve"] = generate_serve_grafana_dashboard() f.write(content) with open( os.path.join( self._grafana_dashboard_output_dir, "serve_deployment_grafana_dashboard.json", ), "w", ) as f: ( content, self._dashboard_uids["serve_deployment"], ) = generate_serve_deployment_grafana_dashboard() f.write(content) with open( os.path.join( self._grafana_dashboard_output_dir, "serve_llm_grafana_dashboard.json", ), "w", ) as f: ( content, self._dashboard_uids["serve_llm"], ) = generate_serve_llm_grafana_dashboard() f.write(content) with open( os.path.join( self._grafana_dashboard_output_dir, "data_grafana_dashboard.json", ), "w", ) as f: ( content, self._dashboard_uids["data"], ) = generate_data_grafana_dashboard() f.write(content) with open( os.path.join( self._grafana_dashboard_output_dir, "train_grafana_dashboard.json", ), "w", ) as f: ( content, self._dashboard_uids["train"], ) = generate_train_grafana_dashboard() f.write(content) def _create_default_prometheus_configs(self): """ Creates the Prometheus configurations that are by default provided by Ray. """ prometheus_config_output_path = os.path.join( self._metrics_root, "prometheus", "prometheus.yml" ) # Generate the default Prometheus configurations if os.path.exists(prometheus_config_output_path): os.remove(prometheus_config_output_path) os.makedirs(os.path.dirname(prometheus_config_output_path), exist_ok=True) # This code generates the Prometheus config based on the custom temporary root # path set by the user at Ray cluster start up (via --temp-dir). In contrast, # start_prometheus in install_and_start_prometheus.py uses a hardcoded # Prometheus config at PROMETHEUS_CONFIG_INPUT_PATH that always uses "/tmp/ray". # Other than the root path, the config file generated here is identical to that # hardcoded config file. prom_discovery_file_path = os.path.join( self.temp_dir, PROMETHEUS_SERVICE_DISCOVERY_FILE ) with open(prometheus_config_output_path, "w") as f: f.write( PROMETHEUS_YML_TEMPLATE.format( prom_metrics_service_discovery_file_path=prom_discovery_file_path ) ) async def run(self): await super().run() self._create_default_grafana_configs() self._create_default_prometheus_configs() async def _query_prometheus(self, query): async with self.http_session.get( f"{self.prometheus_host}/api/v1/query?query={quote(query)}", headers=self.prometheus_headers, ) as resp: if resp.status == 200: prom_data = await resp.json() return prom_data message = await resp.text() raise PrometheusQueryError(resp.status, message)
MetricsHead
python
kamyu104__LeetCode-Solutions
Python/minimum-operations-to-maximize-last-elements-in-arrays.py
{ "start": 688, "end": 1177 }
class ____(object): def minOperations(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ INF = float("inf") def count(mx1, mx2): return sum(1 if y <= mx1 and x <= mx2 else INF for x, y in itertools.izip(nums1, nums2) if not (x <= mx1 and y <= mx2)) result = min(count(nums1[-1], nums2[-1]), count(nums2[-1], nums1[-1])) return result if result != INF else -1
Solution2
python
getsentry__sentry
src/sentry/releases/endpoints/project_release_setup.py
{ "start": 627, "end": 3060 }
class ____(ProjectEndpoint): publish_status = { "GET": ApiPublishStatus.UNKNOWN, } permission_classes = (ProjectReleasePermission,) def get(self, request: Request, project) -> Response: """ Get list with release setup progress for a project 1. tag an error 2. link a repo 3. associate commits 4. tell sentry about a deploy """ tag_key = "onboard_tag:1:%s" % (project.id) repo_key = "onboard_repo:1:%s" % (project.organization_id) commit_key = "onboard_commit:1:%s" % hash_values([project.organization_id, project.id]) deploy_key = "onboard_deploy:1:%s" % hash_values([project.organization_id, project.id]) onboard_cache = cache.get_many([tag_key, repo_key, commit_key, deploy_key]) tag = onboard_cache.get(tag_key) if tag is None: tag = Group.objects.filter(project=project.id, first_release__isnull=False).exists() cache.set(tag_key, tag, 3600 if tag else 60) repo = onboard_cache.get(repo_key) if repo is None: repo = Repository.objects.filter(organization_id=project.organization_id).exists() cache.set(repo_key, repo, 3600 if repo else 60) commit = onboard_cache.get(commit_key) if commit is None: # only get the last 1000 releases release_ids = ( ReleaseProject.objects.filter(project=project.id) .order_by("-release_id") .values_list("release_id", flat=True) )[:1000] commit = ReleaseCommit.objects.filter( organization_id=project.organization_id, release__id__in=release_ids ).exists() cache.set(commit_key, commit, 3600 if commit else 60) deploy = onboard_cache.get(deploy_key) if deploy is None: deploy = Deploy.objects.filter( organization_id=project.organization_id, release__projects=project.id ).exists() cache.set(deploy_key, deploy, 3600 if deploy else 60) return Response( [ {"step": "tag", "complete": bool(tag)}, {"step": "repo", "complete": bool(repo)}, {"step": "commit", "complete": bool(commit)}, {"step": "deploy", "complete": bool(deploy)}, ] )
ProjectReleaseSetupCompletionEndpoint
python
PrefectHQ__prefect
tests/runner/test_runner.py
{ "start": 3099, "end": 3435 }
class ____: def __init__(self, value: int): self.value = value @flow def instance_method_flow(self, x: int): return self.value + x def instance_on_cancellation(flow, flow_run, state): logger = flow_run_logger(flow_run, flow) logger.info("Instance method flow was cancelled!")
ClassWithInstanceMethod
python
pytorch__pytorch
test/export/test_export.py
{ "start": 15064, "end": 15894 }
class ____(torch.nn.Module): def __init__(self): super().__init__() self.p1 = torch.nn.Parameter(torch.ones(2, 2)) self.p2 = torch.nn.Parameter( CustomTensorPlainOut( CustomTensorPlainOut( torch.Tensor([[0, 0], [0, 1]]), torch.Tensor([[0, 0], [1, 0]]), ), CustomTensorPlainOut( torch.Tensor([[1, 0], [0, 0]]), torch.Tensor([[0, 1], [0, 0]]), ), ) ) def forward(self, x): a = (x + 2 * self.p1 + self.p2).sum().sum() return x + a @unittest.skipIf(IS_WINDOWS, "Windows isn't supported for this case") @unittest.skipIf(not torchdynamo.is_dynamo_supported(), "dynamo isn't support")
InputModuleWithNestedSubclass
python
mlflow__mlflow
tests/store/model_registry/test_file_store.py
{ "start": 38874, "end": 74324 }
class ____(NamedTuple): names: list[str] token: str def _search_registered_models( store, filter_string=None, max_results=10, order_by=None, page_token=None ): result = store.search_registered_models( filter_string=filter_string, max_results=max_results, order_by=order_by, page_token=page_token, ) return SearchRegisteredModelsResult( names=[registered_model.name for registered_model in result], token=result.token, ) def test_search_registered_models(store): # create some registered models prefix = "test_for_search_" names = [prefix + name for name in ["RM1", "RM2", "RM3", "RM4", "RM4A", "RM4ab"]] for name in names: store.create_registered_model(name) # search with no filter should return all registered models res = _search_registered_models(store, None) assert res.names == names # equality search using name should return exactly the 1 name res = _search_registered_models(store, f"name='{names[0]}'") assert res.names == [names[0]] # equality search using name that is not valid should return nothing res = _search_registered_models(store, f"name='{names[0]}cats'") assert res.names == [] # case-sensitive prefix search using LIKE should return all the RMs res = _search_registered_models(store, f"name LIKE '{prefix}%'") assert res.names == names # case-sensitive prefix search using LIKE with surrounding % should return all the RMs res = _search_registered_models(store, "name LIKE '%RM%'") assert res.names == names # case-sensitive prefix search using LIKE with surrounding % should return all the RMs # _e% matches test_for_search_ , so all RMs should match res = _search_registered_models(store, "name LIKE '_e%'") assert res.names == names # case-sensitive prefix search using LIKE should return just rm4 res = _search_registered_models(store, f"name LIKE '{prefix}RM4A%'") assert res.names == [names[4]] # case-sensitive prefix search using LIKE should return no models if no match res = _search_registered_models(store, f"name LIKE '{prefix}cats%'") assert res.names == [] # confirm that LIKE is not case-sensitive res = _search_registered_models(store, "name lIkE '%blah%'") assert res.names == [] res = _search_registered_models(store, f"name like '{prefix}RM4A%'") assert res.names == [names[4]] # case-insensitive prefix search using ILIKE should return both rm5 and rm6 res = _search_registered_models(store, f"name ILIKE '{prefix}RM4A%'") assert res.names == names[4:] # case-insensitive postfix search with ILIKE res = _search_registered_models(store, "name ILIKE '%RM4a%'") assert res.names == names[4:] # case-insensitive prefix search using ILIKE should return both rm5 and rm6 res = _search_registered_models(store, f"name ILIKE '{prefix}cats%'") assert res.names == [] # confirm that ILIKE is not case-sensitive res = _search_registered_models(store, "name iLike '%blah%'") assert res.names == [] # confirm that ILIKE works for empty query res = _search_registered_models(store, "name iLike '%%'") assert res.names == names res = _search_registered_models(store, "name ilike '%RM4a%'") assert res.names == names[4:] # cannot search by invalid comparator types with pytest.raises( MlflowException, match="Parameter value is either not quoted or unidentified quote types used for " "string value something", ) as exception_context: _search_registered_models(store, "name!=something") assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) # cannot search by run_id with pytest.raises( MlflowException, match=r"Invalid attribute key 'run_id' specified. Valid keys are '{'name'}'", ) as exception_context: _search_registered_models(store, "run_id='somerunID'") assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) # cannot search by source_path with pytest.raises( MlflowException, match=r"Invalid attribute key 'source_path' specified\. Valid keys are '{'name'}'", ) as exception_context: _search_registered_models(store, "source_path = 'A/D'") assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) # cannot search by other params with pytest.raises( MlflowException, match=r"Invalid clause\(s\) in filter string" ) as exception_context: _search_registered_models(store, "evilhax = true") assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) # delete last registered model. search should not return the first 5 store.delete_registered_model(name=names[-1]) res = _search_registered_models(store, None, max_results=1000) assert res.names == names[:-1] assert res.token is None # equality search using name should return no names assert _search_registered_models(store, f"name='{names[-1]}'") == ([], None) # case-sensitive prefix search using LIKE should return all the RMs res = _search_registered_models(store, f"name LIKE '{prefix}%'") assert res.names == names[0:5] assert res.token is None # case-insensitive prefix search using ILIKE should return both rm5 and rm6 res = _search_registered_models(store, f"name ILIKE '{prefix}RM4A%'") assert res.names == [names[4]] assert res.token is None def test_search_registered_models_by_tag(store): name1 = "test_for_search_RM_by_tag1" name2 = "test_for_search_RM_by_tag2" tags1 = [ RegisteredModelTag("t1", "abc"), RegisteredModelTag("t2", "xyz"), ] tags2 = [ RegisteredModelTag("t1", "abcd"), RegisteredModelTag("t2", "xyz123"), RegisteredModelTag("t3", "XYZ"), ] store.create_registered_model(name1, tags1) store.create_registered_model(name2, tags2) res = _search_registered_models(store, "tag.t3 = 'XYZ'") assert res.names == [name2] res = _search_registered_models(store, f"name = '{name1}' and tag.t1 = 'abc'") assert res.names == [name1] res = _search_registered_models(store, "tag.t1 LIKE 'ab%'") assert res.names == [name1, name2] res = _search_registered_models(store, "tag.t1 ILIKE 'aB%'") assert res.names == [name1, name2] res = _search_registered_models(store, "tag.t1 LIKE 'ab%' AND tag.t2 LIKE 'xy%'") assert res.names == [name1, name2] res = _search_registered_models(store, "tag.t3 = 'XYz'") assert res.names == [] res = _search_registered_models(store, "tag.T3 = 'XYZ'") assert res.names == [] res = _search_registered_models(store, "tag.t1 != 'abc'") assert res.names == [name2] # test filter with duplicated keys res = _search_registered_models(store, "tag.t1 != 'abcd' and tag.t1 LIKE 'ab%'") assert res.names == [name1] def test_search_registered_models_order_by_simple(store): # create some registered models names = ["RM1", "RM2", "RM3", "RM4", "RM4A", "RM4ab"] for name in names: store.create_registered_model(name) time.sleep(0.001) # sleep for windows store timestamp precision issues # by default order by name ASC res = _search_registered_models(store) assert res.names == names # order by name DESC res = _search_registered_models(store, order_by=["name DESC"]) assert res.names == names[::-1] # order by last_updated_timestamp ASC store.update_registered_model(names[0], "latest updated") res = _search_registered_models(store, order_by=["last_updated_timestamp ASC"]) assert res.names[-1] == names[0] def test_search_registered_model_pagination(store): rms = [store.create_registered_model(f"RM{i:03}").name for i in range(50)] # test flow with fixed max_results returned_rms = [] query = "name LIKE 'RM%'" res = _search_registered_models(store, query, page_token=None, max_results=5) returned_rms.extend(res.names) while res.token: res = _search_registered_models(store, query, page_token=res.token, max_results=5) returned_rms.extend(res.names) assert returned_rms == rms # test that pagination will return all valid results in sorted order # by name ascending res = _search_registered_models(store, query, max_results=5) assert res.token is not None assert res.names == rms[0:5] res = _search_registered_models(store, query, page_token=res.token, max_results=10) assert res.token is not None assert res.names == rms[5:15] res = _search_registered_models(store, query, page_token=res.token, max_results=20) assert res.token is not None assert res.names == rms[15:35] res = _search_registered_models(store, query, page_token=res.token, max_results=100) # assert that page token is None assert res.token is None assert res.names == rms[35:] # test that providing a completely invalid page token throws with pytest.raises( MlflowException, match=r"Invalid page token, could not base64-decode" ) as exception_context: _search_registered_models(store, query, page_token="evilhax", max_results=20) assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) # test that providing too large of a max_results throws with pytest.raises( MlflowException, match=r"Invalid value for max_results." ) as exception_context: _search_registered_models(store, query, page_token="evilhax", max_results=1e15) assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) def test_search_registered_model_order_by(store): rms = [] # explicitly mock the creation_timestamps because timestamps seem to be unstable in Windows for i in range(50): rms.append(store.create_registered_model(f"RM{i:03}").name) time.sleep(0.01) # test flow with fixed max_results and order_by (test stable order across pages) returned_rms = [] query = "name LIKE 'RM%'" result, token = _search_registered_models( store, query, page_token=None, order_by=["name DESC"], max_results=5 ) returned_rms.extend(result) while token: result, token = _search_registered_models( store, query, page_token=token, order_by=["name DESC"], max_results=5 ) returned_rms.extend(result) # name descending should be the opposite order of the current order assert returned_rms == rms[::-1] # last_updated_timestamp descending should have the newest RMs first res = _search_registered_models( store, query, page_token=None, order_by=["last_updated_timestamp DESC"], max_results=100, ) assert res.names == rms[::-1] # last_updated_timestamp ascending should have the oldest RMs first res = _search_registered_models( store, query, page_token=None, order_by=["last_updated_timestamp ASC"], max_results=100, ) assert res.names == rms # name ascending should have the original order res = _search_registered_models( store, query, page_token=None, order_by=["name ASC"], max_results=100 ) assert res.names == rms # test that no ASC/DESC defaults to ASC res = _search_registered_models( store, query, page_token=None, order_by=["last_updated_timestamp"], max_results=100, ) assert res.names == rms with mock.patch( "mlflow.store.model_registry.file_store.get_current_time_millis", return_value=1 ): rm1 = store.create_registered_model("MR1").name rm2 = store.create_registered_model("MR2").name with mock.patch( "mlflow.store.model_registry.file_store.get_current_time_millis", return_value=2 ): rm3 = store.create_registered_model("MR3").name rm4 = store.create_registered_model("MR4").name query = "name LIKE 'MR%'" # test with multiple clauses res = _search_registered_models( store, query, page_token=None, order_by=["last_updated_timestamp ASC", "name DESC"], max_results=100, ) assert res.names == [rm2, rm1, rm4, rm3] # confirm that name ascending is the default, even if ties exist on other fields res = _search_registered_models(store, query, page_token=None, order_by=[], max_results=100) assert res.names == [rm1, rm2, rm3, rm4] # test default tiebreak with descending timestamps res = _search_registered_models( store, query, page_token=None, order_by=["last_updated_timestamp DESC"], max_results=100, ) assert res.names == [rm3, rm4, rm1, rm2] def test_search_registered_model_order_by_errors(store): store.create_registered_model("dummy") query = "name LIKE 'RM%'" # test that invalid columns throw even if they come after valid columns with pytest.raises( MlflowException, match="Invalid attribute key 'description' specified." ) as exception_context: _search_registered_models( store, query, page_token=None, order_by=["name ASC", "description DESC"], max_results=5, ) assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) # test that invalid columns with random text throw even if they come after valid columns with pytest.raises(MlflowException, match=r"Invalid order_by clause '.+'") as exception_context: _search_registered_models( store, query, page_token=None, order_by=["name ASC", "last_updated_timestamp DESC blah"], max_results=5, ) assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) def test_set_model_version_tag(store): name1 = "SetModelVersionTag_TestMod" name2 = "SetModelVersionTag_TestMod 2" initial_tags = [ ModelVersionTag("key", "value"), ModelVersionTag("anotherKey", "some other value"), ] store.create_registered_model(name1) store.create_registered_model(name2) run_id_1 = uuid.uuid4().hex run_id_2 = uuid.uuid4().hex run_id_3 = uuid.uuid4().hex store.create_model_version(name1, "A/B", run_id_1, initial_tags) store.create_model_version(name1, "A/C", run_id_2, initial_tags) store.create_model_version(name2, "A/D", run_id_3, initial_tags) new_tag = ModelVersionTag("randomTag", "not a random value") store.set_model_version_tag(name1, 1, new_tag) all_tags = [*initial_tags, new_tag] rm1mv1 = store.get_model_version(name1, 1) assert rm1mv1.tags == {tag.key: tag.value for tag in all_tags} # test overriding a tag with the same key overriding_tag = ModelVersionTag("key", "overriding") store.set_model_version_tag(name1, 1, overriding_tag) all_tags = [tag for tag in all_tags if tag.key != "key"] + [overriding_tag] rm1mv1 = store.get_model_version(name1, 1) assert rm1mv1.tags == {tag.key: tag.value for tag in all_tags} # does not affect other model versions with the same key rm1mv2 = store.get_model_version(name1, 2) rm2mv1 = store.get_model_version(name2, 1) assert rm1mv2.tags == {tag.key: tag.value for tag in initial_tags} assert rm2mv1.tags == {tag.key: tag.value for tag in initial_tags} # can not set tag on deleted (non-existed) model version store.delete_model_version(name1, 2) with pytest.raises( MlflowException, match=rf"Model Version \(name={name1}, version=2\) not found" ) as exception_context: store.set_model_version_tag(name1, 2, overriding_tag) assert exception_context.value.error_code == ErrorCode.Name(RESOURCE_DOES_NOT_EXIST) # test cannot set tags that are too long long_tag = ModelVersionTag("longTagKey", "a" * 100_001) with pytest.raises( MlflowException, match=r"'value' exceeds the maximum length of \d+ characters", ) as exception_context: store.set_model_version_tag(name1, 1, long_tag) assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) # test can set tags that are somewhat long long_tag = ModelVersionTag("longTagKey", "a" * 4999) store.set_model_version_tag(name1, 1, long_tag) # can not set invalid tag with pytest.raises( MlflowException, match=r"Missing value for required parameter 'key'" ) as exception_context: store.set_model_version_tag(name2, 1, ModelVersionTag(key=None, value="")) assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) # can not use invalid model name or version with pytest.raises( MlflowException, match=r"Missing value for required parameter 'name'\." ) as exception_context: store.set_model_version_tag(None, 1, ModelVersionTag(key="key", value="value")) assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) with pytest.raises( MlflowException, match=r"Parameter 'version' must be an integer, got 'I am not a version'.", ) as exception_context: store.set_model_version_tag( name2, "I am not a version", ModelVersionTag(key="key", value="value") ) assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) def test_delete_model_version_tag(store): name1 = "DeleteModelVersionTag_TestMod" name2 = "DeleteModelVersionTag_TestMod 2" initial_tags = [ ModelVersionTag("key", "value"), ModelVersionTag("anotherKey", "some other value"), ] store.create_registered_model(name1) store.create_registered_model(name2) run_id_1 = uuid.uuid4().hex run_id_2 = uuid.uuid4().hex run_id_3 = uuid.uuid4().hex store.create_model_version(name1, "A/B", run_id_1, initial_tags) store.create_model_version(name1, "A/C", run_id_2, initial_tags) store.create_model_version(name2, "A/D", run_id_3, initial_tags) new_tag = ModelVersionTag("randomTag", "not a random value") store.set_model_version_tag(name1, 1, new_tag) store.delete_model_version_tag(name1, 1, "randomTag") rm1mv1 = store.get_model_version(name1, 1) assert rm1mv1.tags == {tag.key: tag.value for tag in initial_tags} # testing deleting a key does not affect other model versions with the same key store.delete_model_version_tag(name1, 1, "key") rm1mv1 = store.get_model_version(name1, 1) rm1mv2 = store.get_model_version(name1, 2) rm2mv1 = store.get_model_version(name2, 1) assert rm1mv1.tags == {"anotherKey": "some other value"} assert rm1mv2.tags == {tag.key: tag.value for tag in initial_tags} assert rm2mv1.tags == {tag.key: tag.value for tag in initial_tags} # delete tag that is already deleted does nothing store.delete_model_version_tag(name1, 1, "key") rm1mv1 = store.get_model_version(name1, 1) assert rm1mv1.tags == {"anotherKey": "some other value"} # can not delete tag on deleted (non-existed) model version store.delete_model_version(name2, 1) with pytest.raises( MlflowException, match=rf"Model Version \(name={name2}, version=1\) not found" ) as exception_context: store.delete_model_version_tag(name2, 1, "key") assert exception_context.value.error_code == ErrorCode.Name(RESOURCE_DOES_NOT_EXIST) # can not delete tag with invalid key with pytest.raises( MlflowException, match=r"Missing value for required parameter 'key'" ) as exception_context: store.delete_model_version_tag(name1, 2, None) assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) # can not use invalid model name or version with pytest.raises( MlflowException, match=r"Missing value for required parameter 'name'\." ) as exception_context: store.delete_model_version_tag(None, 2, "key") assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) with pytest.raises( MlflowException, match=r"Parameter 'version' must be an integer, got 'I am not a version'\." ) as exception_context: store.delete_model_version_tag(name1, "I am not a version", "key") assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE) def _setup_and_test_aliases(store, model_name): store.create_registered_model(model_name) run_id_1 = uuid.uuid4().hex run_id_2 = uuid.uuid4().hex store.create_model_version(model_name, "v1", run_id_1) store.create_model_version(model_name, "v2", run_id_2) store.set_registered_model_alias(model_name, "test_alias", "2") model = store.get_registered_model(model_name) assert model.aliases == {"test_alias": "2"} mv1 = store.get_model_version(model_name, 1) mv2 = store.get_model_version(model_name, 2) assert mv1.aliases == [] assert mv2.aliases == ["test_alias"] def test_set_registered_model_alias(store): _setup_and_test_aliases(store, "SetRegisteredModelAlias_TestMod") def test_delete_registered_model_alias(store): model_name = "DeleteRegisteredModelAlias_TestMod" _setup_and_test_aliases(store, model_name) store.delete_registered_model_alias(model_name, "test_alias") model = store.get_registered_model(model_name) assert model.aliases == {} mv2 = store.get_model_version(model_name, 2) assert mv2.aliases == [] with pytest.raises(MlflowException, match=r"Registered model alias test_alias not found."): store.get_model_version_by_alias(model_name, "test_alias") def test_get_model_version_by_alias(store): model_name = "GetModelVersionByAlias_TestMod" _setup_and_test_aliases(store, model_name) mv = store.get_model_version_by_alias(model_name, "test_alias") assert mv.aliases == ["test_alias"] def test_delete_model_version_deletes_alias(store): model_name = "DeleteModelVersionDeletesAlias_TestMod" _setup_and_test_aliases(store, model_name) store.delete_model_version(model_name, 2) model = store.get_registered_model(model_name) assert model.aliases == {} with pytest.raises(MlflowException, match=r"Registered model alias test_alias not found."): store.get_model_version_by_alias(model_name, "test_alias") def test_delete_model_deletes_alias(store): model_name = "DeleteModelDeletesAlias_TestMod" _setup_and_test_aliases(store, model_name) store.delete_registered_model(model_name) with pytest.raises( MlflowException, match=r"Registered Model with name=DeleteModelDeletesAlias_TestMod not found", ): store.get_model_version_by_alias(model_name, "test_alias") def test_pyfunc_model_registry_with_file_store(store): import mlflow from mlflow.pyfunc import PythonModel class MyModel(PythonModel): def predict(self, context, model_input, params=None): return 7 mlflow.set_registry_uri(path_to_local_file_uri(store.root_directory)) with mlflow.start_run(): mlflow.pyfunc.log_model(name="foo", python_model=MyModel(), registered_model_name="model1") mlflow.pyfunc.log_model(name="foo", python_model=MyModel(), registered_model_name="model2") mlflow.pyfunc.log_model( name="model", python_model=MyModel(), registered_model_name="model1" ) with mlflow.start_run(): mlflow.log_param("A", "B") models = store.search_registered_models(max_results=10) assert len(models) == 2 assert models[0].name == "model1" assert models[1].name == "model2" mv1 = store.search_model_versions("name = 'model1'", max_results=10) assert len(mv1) == 2 assert mv1[0].name == "model1" mv2 = store.search_model_versions("name = 'model2'", max_results=10) assert len(mv2) == 1 assert mv2[0].name == "model2" @pytest.mark.parametrize("copy_to_same_model", [False, True]) def test_copy_model_version(store, copy_to_same_model): name1 = "test_for_copy_MV1" store.create_registered_model(name1) src_tags = [ ModelVersionTag("key", "value"), ModelVersionTag("anotherKey", "some other value"), ] src_mv = _create_model_version( store, name1, tags=src_tags, run_link="dummylink", description="test description", ) # Make some changes to the src MV that won't be copied over store.transition_model_version_stage( name1, src_mv.version, "Production", archive_existing_versions=False ) copy_rm_name = name1 if copy_to_same_model else "test_for_copy_MV2" copy_mv_version = 2 if copy_to_same_model else 1 timestamp = time.time() dst_mv = store.copy_model_version(src_mv, copy_rm_name) assert dst_mv.name == copy_rm_name assert dst_mv.version == copy_mv_version copied_mv = store.get_model_version(dst_mv.name, dst_mv.version) assert copied_mv.name == copy_rm_name assert copied_mv.version == copy_mv_version assert copied_mv.current_stage == "None" assert copied_mv.creation_timestamp >= timestamp assert copied_mv.last_updated_timestamp >= timestamp assert copied_mv.description == "test description" assert copied_mv.source == f"models:/{src_mv.name}/{src_mv.version}" assert store.get_model_version_download_uri(dst_mv.name, dst_mv.version) == src_mv.source assert copied_mv.run_link == "dummylink" assert copied_mv.run_id == src_mv.run_id assert copied_mv.status == "READY" assert copied_mv.status_message is None assert copied_mv.tags == {"key": "value", "anotherKey": "some other value"} # Copy a model version copy double_copy_mv = store.copy_model_version(copied_mv, "test_for_copy_MV3") assert double_copy_mv.source == f"models:/{copied_mv.name}/{copied_mv.version}" assert store.get_model_version_download_uri(dst_mv.name, dst_mv.version) == src_mv.source def test_writing_model_version_preserves_storage_location(store): name = "test_storage_location_MV1" source = "/special/source" store.create_registered_model(name) _create_model_version(store, name, source=source) _create_model_version(store, name, source=source) # Run through all the operations that modify model versions and make sure that the # `storage_location` property is not dropped. store.transition_model_version_stage(name, 1, "Production", archive_existing_versions=False) assert store._fetch_file_model_version_if_exists(name, 1).storage_location == source store.update_model_version(name, 1, description="test description") assert store._fetch_file_model_version_if_exists(name, 1).storage_location == source store.transition_model_version_stage(name, 1, "Production", archive_existing_versions=True) assert store._fetch_file_model_version_if_exists(name, 1).storage_location == source store.rename_registered_model(name, "test_storage_location_new") assert ( store._fetch_file_model_version_if_exists("test_storage_location_new", 1).storage_location == source ) def test_search_prompts(store): store.create_registered_model("model", tags=[RegisteredModelTag(key="fruit", value="apple")]) store.create_registered_model( "prompt_1", tags=[RegisteredModelTag(key=IS_PROMPT_TAG_KEY, value="true")] ) store.create_registered_model( "prompt_2", tags=[ RegisteredModelTag(key=IS_PROMPT_TAG_KEY, value="true"), RegisteredModelTag(key="fruit", value="apple"), ], ) # By default, should not return prompts rms = store.search_registered_models(max_results=10) assert len(rms) == 1 assert rms[0].name == "model" rms = store.search_registered_models(filter_string="tags.fruit = 'apple'", max_results=10) assert len(rms) == 1 assert rms[0].name == "model" rms = store.search_registered_models(filter_string="name = 'prompt_1'", max_results=10) assert len(rms) == 0 rms = store.search_registered_models( filter_string="tags.`mlflow.prompt.is_prompt` = 'false'", max_results=10 ) assert len(rms) == 1 assert rms[0].name == "model" rms = store.search_registered_models( filter_string="tags.`mlflow.prompt.is_prompt` != 'true'", max_results=10 ) assert len(rms) == 1 assert rms[0].name == "model" # Search for prompts rms = store.search_registered_models( filter_string="tags.`mlflow.prompt.is_prompt` = 'true'", max_results=10 ) assert len(rms) == 2 assert {rm.name for rm in rms} == {"prompt_1", "prompt_2"} rms = store.search_registered_models( filter_string="name = 'prompt_1' and tags.`mlflow.prompt.is_prompt` = 'true'", max_results=10, ) assert len(rms) == 1 assert rms[0].name == "prompt_1" rms = store.search_registered_models( filter_string="tags.`mlflow.prompt.is_prompt` = 'true' and tags.fruit = 'apple'", max_results=10, ) assert len(rms) == 1 assert rms[0].name == "prompt_2" def test_search_prompts_versions(store): # A Model store.create_registered_model("model") store.create_model_version( "model", "1", "dummy_source", tags=[ModelVersionTag(key="fruit", value="apple")] ) # A Prompt with 1 version store.create_registered_model( "prompt_1", tags=[RegisteredModelTag(key=IS_PROMPT_TAG_KEY, value="true")] ) store.create_model_version( "prompt_1", "1", "dummy_source", tags=[ModelVersionTag(key=IS_PROMPT_TAG_KEY, value="true")] ) # A Prompt with 2 versions store.create_registered_model( "prompt_2", tags=[RegisteredModelTag(key=IS_PROMPT_TAG_KEY, value="true")], ) store.create_model_version( "prompt_2", "1", "dummy_source", tags=[ ModelVersionTag(key=IS_PROMPT_TAG_KEY, value="true"), ModelVersionTag(key="fruit", value="apple"), ], ) store.create_model_version( "prompt_2", "2", "dummy_source", tags=[ ModelVersionTag(key=IS_PROMPT_TAG_KEY, value="true"), ModelVersionTag(key="fruit", value="orange"), ], ) # Searching model versions should not return prompts by default either mvs = store.search_model_versions(max_results=10) assert len(mvs) == 1 assert mvs[0].name == "model" mvs = store.search_model_versions(filter_string="tags.fruit = 'apple'", max_results=10) assert len(mvs) == 1 assert mvs[0].name == "model" mvs = store.search_model_versions( filter_string="tags.`mlflow.prompt.is_prompt` = 'false'", max_results=10 ) assert len(mvs) == 1 assert mvs[0].name == "model" mvs = store.search_model_versions( filter_string="tags.`mlflow.prompt.is_prompt` != 'true'", max_results=10 ) assert len(mvs) == 1 assert mvs[0].name == "model" # Search for prompts via search_model_versions mvs = store.search_model_versions( filter_string="tags.`mlflow.prompt.is_prompt` = 'true'", max_results=10 ) assert len(mvs) == 3 mvs = store.search_model_versions( filter_string="tags.`mlflow.prompt.is_prompt` = 'true' and name = 'prompt_2'", max_results=10, ) assert len(mvs) == 2 mvs = store.search_model_versions( filter_string="tags.`mlflow.prompt.is_prompt` = 'true' and tags.fruit = 'apple'", max_results=10, ) assert len(mvs) == 1 assert mvs[0].name == "prompt_2" def test_create_registered_model_handle_prompt_properly(store): prompt_tags = [RegisteredModelTag(key=IS_PROMPT_TAG_KEY, value="true")] store.create_registered_model("model") store.create_registered_model("prompt", tags=prompt_tags) with pytest.raises(MlflowException, match=r"Registered Model \(name=model\) already exists"): store.create_registered_model("model") with pytest.raises(MlflowException, match=r"Prompt \(name=prompt\) already exists"): store.create_registered_model("prompt", tags=prompt_tags) with pytest.raises( MlflowException, match=r"Tried to create a prompt with name 'model', " r"but the name is already taken by a registered model.", ): store.create_registered_model("model", tags=prompt_tags) with pytest.raises( MlflowException, match=r"Tried to create a registered model with name 'prompt', " r"but the name is already taken by a prompt.", ): store.create_registered_model("prompt") def test_create_model_version_with_model_id_and_no_run_id(store: FileStore): class SimpleModel(PythonModel): def predict(self, context, model_input, params=None): return model_input name = "test_model_with_model_id" store.create_registered_model(name) with mlflow.start_run() as run: model_info = mlflow.pyfunc.log_model( name="model", python_model=SimpleModel(), ) run_id = run.info.run_id model_id = model_info.model_id mv = store.create_model_version( name=name, source="/absolute/path/to/source", run_id=None, model_id=model_id, ) assert mv.run_id == run_id mvd = store.get_model_version(name=mv.name, version=mv.version) assert mvd.run_id == run_id def test_update_model_version_with_model_id_and_metrics(store: FileStore): class SimpleModel(PythonModel): def predict(self, context, model_input, params=None): return model_input name = "test_model_with_model_id_and_metrics" store.create_registered_model(name) with mlflow.start_run() as run: mlflow.log_param("learning_rate", "0.001") model_info = mlflow.pyfunc.log_model( name="model", python_model=SimpleModel(), ) mlflow.log_metric("execution_time", 33.74682, step=0, model_id=model_info.model_id) run_id = run.info.run_id model_id = model_info.model_id mv = store.create_model_version( name=name, source="/absolute/path/to/source", run_id=None, model_id=model_id, ) assert mv.run_id == run_id mvd = store.get_model_version(name=mv.name, version=mv.version) assert mvd.run_id == run_id assert mvd.metrics is not None assert len(mvd.metrics) == 1 assert mvd.metrics[0].key == "execution_time" assert mvd.metrics[0].value == 33.74682 assert mvd.params == {"learning_rate": "0.001"} updated_mvd = store.update_model_version( name=mv.name, version=mv.version, description="Test description with metrics", ) assert updated_mvd.description == "Test description with metrics" retrieved_mvd = store.get_model_version(name=mv.name, version=mv.version) assert retrieved_mvd.description == "Test description with metrics" assert retrieved_mvd.metrics is not None assert len(retrieved_mvd.metrics) == 1 assert retrieved_mvd.metrics[0].key == "execution_time" assert retrieved_mvd.params == {"learning_rate": "0.001"}
SearchRegisteredModelsResult
python
google__jax
tests/lax_numpy_setops_test.py
{ "start": 3417, "end": 16527 }
class ____(jtu.JaxTestCase): """Tests of set-like operations from jax.numpy.""" @jtu.sample_product( element_shape=all_shapes, test_shape=all_shapes, dtype=default_dtypes, invert=[False, True], method=['auto', 'compare_all', 'binary_search', 'sort'] ) def testIsin(self, element_shape, test_shape, dtype, invert, method): rng = jtu.rand_default(self.rng()) args_maker = lambda: [rng(element_shape, dtype), rng(test_shape, dtype)] jnp_fun = lambda e, t: jnp.isin(e, t, invert=invert, method=method) np_fun = lambda e, t: np.isin(e, t, invert=invert) self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker) self._CompileAndCheck(jnp_fun, args_maker) @jtu.sample_product( dtype1=[s for s in default_dtypes if s != jnp.bfloat16], dtype2=[s for s in default_dtypes if s != jnp.bfloat16], shape1=all_shapes, shape2=all_shapes, overlap=[0.1, 0.5, 0.9], ) def testSetdiff1d(self, shape1, shape2, dtype1, dtype2, overlap): args_maker = partial(arrays_with_overlapping_values, self.rng(), shapes=[shape1, shape2], dtypes=[dtype1, dtype2], overlap=overlap) with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]): self._CheckAgainstNumpy(np.setdiff1d, jnp.setdiff1d, args_maker) @jtu.sample_product( dtype1=[s for s in default_dtypes if s != jnp.bfloat16], dtype2=[s for s in default_dtypes if s != jnp.bfloat16], shape1=all_shapes, shape2=all_shapes, size=[1, 5, 10], fill_value=[None, -1], overlap=[0.1, 0.5, 0.9], ) def testSetdiff1dSize(self, shape1, shape2, dtype1, dtype2, size, fill_value, overlap): args_maker = partial(arrays_with_overlapping_values, self.rng(), shapes=[shape1, shape2], dtypes=[dtype1, dtype2], overlap=overlap) def np_fun(arg1, arg2): result = np.setdiff1d(arg1, arg2) if size <= len(result): return result[:size] else: return np.pad(result, (0, size-len(result)), constant_values=fill_value or 0) def jnp_fun(arg1, arg2): return jnp.setdiff1d(arg1, arg2, size=size, fill_value=fill_value) with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]): self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker) self._CompileAndCheck(jnp_fun, args_maker) @jtu.sample_product( shape1=all_shapes, shape2=all_shapes, ) def testSetdiff1dAssumeUnique(self, shape1, shape2): # regression test for https://github.com/jax-ml/jax/issues/32335 args_maker = lambda: (jnp.arange(math.prod(shape1), dtype='int32').reshape(shape1), jnp.arange(math.prod(shape2), dtype='int32').reshape(shape2)) np_op = partial(np.setdiff1d, assume_unique=True) jnp_op = partial(jnp.setdiff1d, assume_unique=True) self._CheckAgainstNumpy(np_op, jnp_op, args_maker) @jtu.sample_product( dtype1=[s for s in default_dtypes if s != jnp.bfloat16], dtype2=[s for s in default_dtypes if s != jnp.bfloat16], shape1=all_shapes, shape2=all_shapes, overlap=[0.1, 0.5, 0.9], ) def testUnion1d(self, shape1, shape2, dtype1, dtype2, overlap): args_maker = partial(arrays_with_overlapping_values, self.rng(), shapes=[shape1, shape2], dtypes=[dtype1, dtype2], overlap=overlap) def np_fun(arg1, arg2): dtype = jnp.promote_types(arg1.dtype, arg2.dtype) return np.union1d(arg1, arg2).astype(dtype) with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]): self._CheckAgainstNumpy(np_fun, jnp.union1d, args_maker) @jtu.sample_product( dtype1=[s for s in default_dtypes if s != jnp.bfloat16], dtype2=[s for s in default_dtypes if s != jnp.bfloat16], shape1=nonempty_shapes, shape2=nonempty_shapes, size=[1, 5, 10], fill_value=[None, -1], overlap=[0.1, 0.5, 0.9], ) def testUnion1dSize(self, shape1, shape2, dtype1, dtype2, size, fill_value, overlap): args_maker = partial(arrays_with_overlapping_values, self.rng(), shapes=[shape1, shape2], dtypes=[dtype1, dtype2], overlap=overlap) def np_fun(arg1, arg2): dtype = jnp.promote_types(arg1.dtype, arg2.dtype) result = np.union1d(arg1, arg2).astype(dtype) fv = result.min() if fill_value is None else fill_value if size <= len(result): return result[:size] else: return np.concatenate([result, np.full(size - len(result), fv, result.dtype)]) def jnp_fun(arg1, arg2): return jnp.union1d(arg1, arg2, size=size, fill_value=fill_value) with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]): self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker) self._CompileAndCheck(jnp_fun, args_maker) @jtu.sample_product( dtype1=[s for s in default_dtypes if s != jnp.bfloat16], dtype2=[s for s in default_dtypes if s != jnp.bfloat16], shape1=all_shapes, shape2=all_shapes, assume_unique=[False, True], size=[None, 2, 5], fill_value=[None, 99], overlap=[0.1, 0.5, 0.9], ) def testSetxor1d(self, shape1, dtype1, shape2, dtype2, assume_unique, size, fill_value, overlap): args_maker = partial(arrays_with_overlapping_values, self.rng(), shapes=[shape1, shape2], dtypes=[dtype1, dtype2], overlap=overlap) jnp_fun = lambda ar1, ar2: jnp.setxor1d(ar1, ar2, assume_unique=assume_unique, size=size, fill_value=fill_value) def np_fun(ar1, ar2): if assume_unique: # numpy requires 1D inputs when assume_unique is True. ar1 = np.ravel(ar1) ar2 = np.ravel(ar2) return with_size_argument(np.setxor1d)(ar1, ar2, assume_unique, size=size, fill_value=fill_value) with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]): self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False) @jtu.sample_product( dtype1=[s for s in default_dtypes if s != jnp.bfloat16], dtype2=[s for s in default_dtypes if s != jnp.bfloat16], shape1=nonempty_shapes, shape2=nonempty_shapes, assume_unique=[False, True], return_indices=[False, True], size=[None, 3, 5], fill_value=[None, -1], overlap=[0.1, 0.5, 0.9], ) def testIntersect1d(self, shape1, dtype1, shape2, dtype2, assume_unique, return_indices, size, fill_value, overlap): args_maker = partial(arrays_with_overlapping_values, self.rng(), shapes=[shape1, shape2], dtypes=[dtype1, dtype2], unique=assume_unique, overlap=overlap) def jnp_fun(ar1, ar2): return jnp.intersect1d(ar1, ar2, assume_unique=assume_unique, return_indices=return_indices, size=size, fill_value=fill_value) def np_fun(ar1, ar2): result = np.intersect1d(ar1, ar2, assume_unique=assume_unique, return_indices=return_indices) def correct_size(x, fill_value): if size is None or size == len(x): return x elif size < len(x): return x[:size] else: if fill_value is None: fill_value = x.min() return np.pad(x, (0, size - len(x)), constant_values=fill_value) if return_indices: return tuple(correct_size(r, f) for r, f in zip(result, [fill_value, ar1.size, ar2.size])) else: return correct_size(result, fill_value) with jtu.strict_promotion_if_dtypes_match([dtype1, dtype2]): self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False) @jtu.sample_product( [dict(shape=shape, axis=axis) for shape in all_shapes for axis in [None] + list(range(len(shape)))], dtype=number_dtypes, return_index=[False, True], return_inverse=[False, True], return_counts=[False, True], ) def testUnique(self, shape, dtype, axis, return_index, return_inverse, return_counts): rng = jtu.rand_some_equal(self.rng()) args_maker = lambda: [rng(shape, dtype)] extra_args = (return_index, return_inverse, return_counts) use_defaults = (False, *(True for arg in extra_args if arg)) if any(extra_args) else False np_fun = jtu.with_jax_dtype_defaults(lambda x: np_unique_backport(x, *extra_args, axis=axis), use_defaults) jnp_fun = lambda x: jnp.unique(x, *extra_args, axis=axis) self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker) @jtu.sample_product(shape=all_shapes, dtype=number_dtypes) def testUniqueAll(self, shape, dtype): rng = jtu.rand_some_equal(self.rng()) args_maker = lambda: [rng(shape, dtype)] self._CheckAgainstNumpy(jnp.unique_all, np.unique_all, args_maker) @jtu.sample_product(shape=all_shapes, dtype=number_dtypes) def testUniqueCounts(self, shape, dtype): rng = jtu.rand_some_equal(self.rng()) args_maker = lambda: [rng(shape, dtype)] self._CheckAgainstNumpy(jnp.unique_counts, np.unique_counts, args_maker) @jtu.sample_product(shape=all_shapes, dtype=number_dtypes) def testUniqueInverse(self, shape, dtype): rng = jtu.rand_some_equal(self.rng()) args_maker = lambda: [rng(shape, dtype)] self._CheckAgainstNumpy(jnp.unique_inverse, np.unique_inverse, args_maker) @jtu.sample_product(shape=all_shapes, dtype=number_dtypes) def testUniqueValues(self, shape, dtype): rng = jtu.rand_some_equal(self.rng()) args_maker = lambda: [rng(shape, dtype)] np_fun = lambda *args: np.sort(np.unique_values(*args)) self._CheckAgainstNumpy(jnp.unique_values, np_fun, args_maker) @jtu.sample_product( [dict(shape=shape, axis=axis) for shape in nonempty_array_shapes for axis in [None] + list(range(len(shape)))], dtype=number_dtypes, size=[1, 5, 10], fill_value=[None, 0, "slice"], ) def testUniqueSize(self, shape, dtype, axis, size, fill_value): rng = jtu.rand_some_equal(self.rng()) args_maker = lambda: [rng(shape, dtype)] kwds = dict(axis=axis, return_index=True, return_inverse=True, return_counts=True) if fill_value == "slice": if axis is None: fill_value = rng((), dtype) else: fill_value = rng(shape[:axis] + shape[axis + 1:], dtype) elif fill_value is not None: fill_value = np.array(fill_value).astype(dtype) @partial(jtu.with_jax_dtype_defaults, use_defaults=(False, True, True, True)) def np_fun(x, fill_value=fill_value): u, ind, inv, counts = np_unique_backport(x, **kwds) axis = kwds['axis'] if axis is None: x = x.ravel() axis = 0 n_unique = u.shape[axis] if size <= u.shape[axis]: slc = (slice(None),) * axis + (slice(size),) u, ind, counts = u[slc], ind[:size], counts[:size] else: extra = (0, size - n_unique) pads = [(0, 0)] * u.ndim pads[axis] = extra u = np.pad(u, pads, constant_values=0) slices = [slice(None)] * u.ndim slices[axis] = slice(1) if fill_value is None: fill_value = u[tuple(slices)] elif np.ndim(fill_value): fill_value = lax.expand_dims(fill_value, (axis,)) slices[axis] = slice(n_unique, None) u[tuple(slices)] = fill_value ind = np.pad(ind, extra, constant_values=ind[0]) counts = np.pad(counts, extra, constant_values=0) return u, ind, inv, counts jnp_fun = lambda x: jnp.unique(x, size=size, fill_value=fill_value, **kwds) self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker) self._CompileAndCheck(jnp_fun, args_maker) @jtu.sample_product(dtype=inexact_dtypes) def testUniqueNans(self, dtype): def args_maker(): x = [-0.0, 0.0, 1.0, 1.0, np.nan, -np.nan] if np.issubdtype(dtype, np.complexfloating): x = [complex(i, j) for i, j in itertools.product(x, repeat=2)] return [np.array(x, dtype=dtype)] kwds = dict(return_index=True, return_inverse=True, return_counts=True) jnp_fun = partial(jnp.unique, **kwds) def np_fun(x): dtype = x.dtype # numpy unique fails for bfloat16 NaNs, so we cast to float64 if x.dtype == jnp.bfloat16: x = x.astype('float64') u, *rest = np.unique(x, **kwds) return (u.astype(dtype), *rest) self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker) @jtu.sample_product(dtype=inexact_dtypes, equal_nan=[True, False]) @jtu.ignore_warning( category=RuntimeWarning, message='invalid value encountered in cast' ) def testUniqueEqualNan(self, dtype, equal_nan): shape = (20,) rng = jtu.rand_some_nan(self.rng()) args_maker = lambda: [rng(shape, dtype)] def np_fun(x): dtype = x.dtype # numpy unique fails for bfloat16 NaNs, so we cast to float64 if x.dtype == jnp.bfloat16: x = x.astype('float64') return np.unique(x, equal_nan=equal_nan).astype(dtype) jnp_fun = partial(jnp.unique, equal_nan=equal_nan) self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker) if __name__ == "__main__": absltest.main(testLoader=jtu.JaxTestLoader())
LaxNumpySetopsTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 35365, "end": 35662 }
class ____(sgqlc.types.Enum): """Properties by which label connections can be ordered. Enumeration Choices: * `CREATED_AT`: Order labels by creation time * `NAME`: Order labels by name """ __schema__ = github_schema __choices__ = ("CREATED_AT", "NAME")
LabelOrderField
python
getsentry__sentry
src/sentry/eventtypes/base.py
{ "start": 1115, "end": 1505 }
class ____(BaseEvent): key = "default" def extract_metadata(self, data): message = strip( get_path(data, "logentry", "formatted") or get_path(data, "logentry", "message") ) if message: title = truncatechars(message.splitlines()[0], 256) else: title = "<unlabeled event>" return {"title": title}
DefaultEvent
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/invalid_selfhosted_gitlab_patch_url/package.py
{ "start": 217, "end": 687 }
class ____(Package): """Package that has GitLab patch URLs that fail auditing.""" homepage = "http://www.example.com" url = "http://www.example.com/patch-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") patch( "https://gitlab.gnome.org/GNOME/glib/-/commit/bda87264372c006c94e21ffb8ff9c50ecb3e14bd.patch", sha256="2e811ec62cb09044c95a4d0213993f09af70cdcc1c709257b33bc9248ae950ed", )
InvalidSelfhostedGitlabPatchUrl
python
getsentry__sentry
src/sentry/snuba/metrics/fields/base.py
{ "start": 31386, "end": 39988 }
class ____(DerivedMetricExpression): # Pretend for the typechecker that __init__ is not overridden, such that # SingularEntityDerivedMetric still has a strongly-typed ctor like its # baseclass. if not TYPE_CHECKING: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) if self.snql is None: raise DerivedMetricParseException( "SnQL cannot be None for instances of SingularEntityDerivedMetric" ) def validate_can_orderby(self) -> None: return @classmethod def __recursively_get_all_entities_in_derived_metric_dependency_tree( cls, derived_metric_mri: str, projects: QuerySet[Project] | Sequence[Project], use_case_id: UseCaseID, ) -> set[MetricEntity]: """ Method that gets the entity of a derived metric by traversing down its dependency tree until it gets to the raw metrics (leaf nodes) then queries snuba to check which entity/entities these raw constituent metrics belong to. """ if derived_metric_mri not in DERIVED_METRICS: return {_get_entity_of_metric_mri(projects, derived_metric_mri, use_case_id)} entities = set() derived_metric = DERIVED_METRICS[derived_metric_mri] for metric_mri in derived_metric.metrics: entities |= cls.__recursively_get_all_entities_in_derived_metric_dependency_tree( metric_mri, projects, use_case_id ) return entities def get_entity( self, projects: QuerySet[Project] | Sequence[Project], use_case_id: UseCaseID ) -> MetricEntity: if not projects: self._raise_entity_validation_exception("get_entity") try: entities = self.__recursively_get_all_entities_in_derived_metric_dependency_tree( derived_metric_mri=self.metric_mri, projects=projects, use_case_id=use_case_id ) except InvalidParams: raise MetricDoesNotExistException() if len(entities) != 1 or entities == {None}: raise DerivedMetricParseException( f"Derived Metric " f"{get_public_name_from_mri(self.metric_mri)} cannot be calculated from a single " f"entity" ) return entities.pop() @classmethod def __recursively_generate_metric_ids( cls, org_id: int, derived_metric_mri: str, use_case_id: UseCaseID ) -> set[int]: """ Method that traverses a derived metric dependency tree to return a set of the metric ids of its constituent metrics """ if derived_metric_mri not in DERIVED_METRICS: return set() derived_metric = DERIVED_METRICS[derived_metric_mri] ids = set() for metric_mri in derived_metric.metrics: if metric_mri not in DERIVED_METRICS: ids.add(resolve_weak(use_case_id, org_id, metric_mri)) else: ids |= cls.__recursively_generate_metric_ids(org_id, metric_mri, use_case_id) return ids def generate_metric_ids(self, projects: Sequence[Project], use_case_id: UseCaseID) -> set[int]: org_id = org_id_from_projects(projects) return self.__recursively_generate_metric_ids( org_id, derived_metric_mri=self.metric_mri, use_case_id=use_case_id ) @classmethod def __recursively_generate_select_snql( cls, project_ids: Sequence[int], org_id: int, derived_metric_mri: str, use_case_id: UseCaseID, alias: str | None = None, ) -> list[Function]: """ Method that generates the SnQL representation for the derived metric """ if derived_metric_mri not in DERIVED_METRICS: return [] derived_metric = DERIVED_METRICS[derived_metric_mri] arg_snql = [] for arg in derived_metric.metrics: arg_snql += cls.__recursively_generate_select_snql( project_ids, org_id, arg, use_case_id ) if alias is None: # Aliases on components of SingularEntityDerivedMetric do not really matter as these evaluate to a single # expression, and so what matters is the alias on that top level expression alias = derived_metric_mri assert derived_metric.snql is not None return [ derived_metric.snql( *arg_snql, project_ids=project_ids, org_id=org_id, metric_ids=cls.__recursively_generate_metric_ids( org_id, derived_metric_mri, use_case_id ), alias=alias, ) ] def generate_select_statements( self, projects: Sequence[Project], use_case_id: UseCaseID, alias: str, params: MetricOperationParams | None = None, ) -> list[Function]: # Before, we are able to generate the relevant SnQL for a derived metric, we need to # validate that this instance of SingularEntityDerivedMetric is built from constituent # metrics that span a single entity if not projects: self._raise_entity_validation_exception("generate_select_statements") self.get_entity(projects=projects, use_case_id=use_case_id) project_ids = [project.id for project in projects] org_id = org_id_from_projects(projects) # Currently `params` is not being used in instances of `SingularEntityDerivedMetric` and # `CompositeEntityDerivedMetric` instances as these types of expressions produce SnQL that does not require any # parameters but in the future that might change, and when that occurs we will need to pass the params to the # `snql` function of the derived metric return self.__recursively_generate_select_snql( project_ids=project_ids, org_id=org_id, derived_metric_mri=self.metric_mri, use_case_id=use_case_id, alias=alias, ) def generate_orderby_clause( self, direction: Direction, projects: Sequence[Project], use_case_id: UseCaseID, alias: str, params: MetricOperationParams | None = None, ) -> list[OrderBy]: if not projects: self._raise_entity_validation_exception("generate_orderby_clause") self.get_entity(projects=projects, use_case_id=use_case_id) return [ OrderBy( self.generate_select_statements( projects=projects, params=params, use_case_id=use_case_id, alias=alias, )[0], direction, ) ] def generate_default_null_values(self) -> int | list[tuple[float]] | None: default_null_value = None try: default_null_value = DEFAULT_AGGREGATES[UNIT_TO_TYPE[self.unit]] except KeyError: pass return default_null_value def run_post_query_function( self, data: SnubaDataType, alias: str, params: MetricOperationParams | None = None, idx: int | None = None, ) -> Any: try: compute_func_args = [data[alias] if idx is None else data[alias][idx]] except KeyError: compute_func_args = [self.generate_default_null_values()] result = self.post_query_func(*compute_func_args) if isinstance(result, tuple) and len(result) == 1: result = result[0] return result def generate_bottom_up_derived_metrics_dependencies( self, alias: str ) -> Iterable[tuple[MetricOperationType | None, str, str]]: return [(None, self.metric_mri, alias)] def generate_groupby_statements( self, projects: Sequence[Project], use_case_id: UseCaseID, alias: str, params: MetricOperationParams | None = None, ) -> list[Function]: raise InvalidParams(f"Cannot group by metric {get_public_name_from_mri(self.metric_mri)}") def generate_where_statements( self, projects: Sequence[Project], use_case_id: UseCaseID, alias: str, params: MetricOperationParams | None = None, ) -> list[Function]: raise InvalidParams(f"Cannot filter by metric {get_public_name_from_mri(self.metric_mri)}")
SingularEntityDerivedMetric
python
facebookresearch__faiss
tests/test_callback_py.py
{ "start": 230, "end": 797 }
class ____(unittest.TestCase): def setUp(self) -> None: super().setUp() def test_timeout(self) -> None: n = 1000 k = 100 d = 128 niter = 1_000_000_000 x = np.random.rand(n, d).astype('float32') index = faiss.IndexFlat(d) cp = faiss.ClusteringParameters() cp.niter = niter cp.verbose = False kmeans = faiss.Clustering(d, k, cp) with self.assertRaises(RuntimeError): with faiss.TimeoutGuard(0.010): kmeans.train(x, index)
TestCallbackPy
python
numba__numba
numba/tests/test_inlining.py
{ "start": 4251, "end": 11520 }
class ____(TestCase): """ Check that jitted inner functions are inlined into outer functions, in nopython mode. Note that not all inner functions are guaranteed to be inlined. We just trust LLVM's inlining heuristics. """ def make_pattern(self, fullname): """ Make regexpr to match mangled name """ parts = fullname.split('.') return r'_ZN?' + r''.join([r'\d+{}'.format(p) for p in parts]) def assert_has_pattern(self, fullname, text): pat = self.make_pattern(fullname) self.assertIsNotNone(re.search(pat, text), msg='expected {}'.format(pat)) def assert_not_has_pattern(self, fullname, text): pat = self.make_pattern(fullname) self.assertIsNone(re.search(pat, text), msg='unexpected {}'.format(pat)) def test_inner_function(self): from numba.tests.inlining_usecases import outer_simple, \ __name__ as prefix with override_config('DUMP_ASSEMBLY', True): with captured_stdout() as out: cfunc = jit((types.int32,), nopython=True)(outer_simple) self.assertPreciseEqual(cfunc(1), 4) # Check the inner function was elided from the output (which also # guarantees it was inlined into the outer function). asm = out.getvalue() self.assert_has_pattern('%s.outer_simple' % prefix, asm) self.assert_not_has_pattern('%s.inner' % prefix, asm) def test_multiple_inner_functions(self): from numba.tests.inlining_usecases import outer_multiple, \ __name__ as prefix # Same with multiple inner functions, and multiple calls to # the same inner function (inner()). This checks that linking in # the same library/module twice doesn't produce linker errors. with override_config('DUMP_ASSEMBLY', True): with captured_stdout() as out: cfunc = jit((types.int32,), nopython=True)(outer_multiple) self.assertPreciseEqual(cfunc(1), 6) asm = out.getvalue() self.assert_has_pattern('%s.outer_multiple' % prefix, asm) self.assert_not_has_pattern('%s.more' % prefix, asm) self.assert_not_has_pattern('%s.inner' % prefix, asm) @skip_parfors_unsupported def test_inline_call_after_parfor(self): from numba.tests.inlining_usecases import __dummy__ # replace the call to make sure inlining doesn't cause label conflict # with parfor body def test_impl(A): __dummy__() return A.sum() j_func = njit(parallel=True, pipeline_class=InlineTestPipeline)( test_impl) A = np.arange(10) self.assertEqual(test_impl(A), j_func(A)) @skip_parfors_unsupported def test_inline_update_target_def(self): def test_impl(a): if a == 1: b = 2 else: b = 3 return b func_ir = compiler.run_frontend(test_impl) blocks = list(func_ir.blocks.values()) for block in blocks: for i, stmt in enumerate(block.body): # match b = 2 and replace with lambda: 2 if (isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Var) and guard(find_const, func_ir, stmt.value) == 2): # replace expr with a dummy call func_ir._definitions[stmt.target.name].remove(stmt.value) stmt.value = ir.Expr.call(ir.Var(block.scope, "myvar", loc=stmt.loc), (), (), stmt.loc) func_ir._definitions[stmt.target.name].append(stmt.value) #func = g.py_func# inline_closure_call(func_ir, {}, block, i, lambda: 2) break self.assertEqual(len(func_ir._definitions['b']), 2) @skip_parfors_unsupported def test_inline_var_dict_ret(self): # make sure inline_closure_call returns the variable replacement dict # and it contains the original variable name used in locals @njit(locals={'b': types.float64}) def g(a): b = a + 1 return b def test_impl(): return g(1) func_ir = compiler.run_frontend(test_impl) blocks = list(func_ir.blocks.values()) for block in blocks: for i, stmt in enumerate(block.body): if (isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr) and stmt.value.op == 'call'): func_def = guard(get_definition, func_ir, stmt.value.func) if (isinstance(func_def, (ir.Global, ir.FreeVar)) and isinstance(func_def.value, CPUDispatcher)): py_func = func_def.value.py_func _, var_map = inline_closure_call( func_ir, py_func.__globals__, block, i, py_func) break self.assertTrue('b' in var_map) @skip_parfors_unsupported def test_inline_call_branch_pruning(self): # branch pruning pass should run properly in inlining to enable # functions with type checks @njit def foo(A=None): if A is None: return 2 else: return A def test_impl(A=None): return foo(A) @register_pass(analysis_only=False, mutates_CFG=True) class PruningInlineTestPass(FunctionPass): _name = "pruning_inline_test_pass" def __init__(self): FunctionPass.__init__(self) def run_pass(self, state): # assuming the function has one block with one call inside assert len(state.func_ir.blocks) == 1 block = list(state.func_ir.blocks.values())[0] for i, stmt in enumerate(block.body): if (guard(find_callname, state.func_ir, stmt.value) is not None): inline_closure_call(state.func_ir, {}, block, i, foo.py_func, state.typingctx, state.targetctx, (state.typemap[stmt.value.args[0].name],), state.typemap, state.calltypes) break return True class InlineTestPipelinePrune(compiler.CompilerBase): def define_pipelines(self): pm = gen_pipeline(self.state, PruningInlineTestPass) pm.finalize() return [pm] # make sure inline_closure_call runs in full pipeline j_func = njit(pipeline_class=InlineTestPipelinePrune)(test_impl) A = 3 self.assertEqual(test_impl(A), j_func(A)) self.assertEqual(test_impl(), j_func()) # make sure IR doesn't have branches fir = j_func.overloads[(types.Omitted(None),)].metadata['preserved_ir'] fir.blocks = simplify_CFG(fir.blocks) self.assertEqual(len(fir.blocks), 1) if __name__ == '__main__': unittest.main()
TestInlining
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/callbackProtocol5.py
{ "start": 1209, "end": 1631 }
class ____(Protocol): def __call__(self, x: int, /, y: str) -> Any: ... def func8(x: int, y: str, /) -> Any: pass def func9(__x: int, __y: str) -> Any: pass # This should generate an error because "y" is position-only # in the source but not the dest. var7: TestClass7 = func8 # This should generate an error because "y" is position-only # in the source but not the dest. var8: TestClass7 = func9
TestClass7
python
apache__airflow
airflow-core/tests/unit/models/test_dagwarning.py
{ "start": 1119, "end": 2796 }
class ____: def setup_method(self): clear_db_dags() def test_purge_inactive_dag_warnings(self, session, testing_dag_bundle): """ Test that the purge_inactive_dag_warnings method deletes inactive dag warnings """ dags = [ DagModel(dag_id="dag_1", bundle_name="testing", is_stale=True), DagModel(dag_id="dag_2", bundle_name="testing", is_stale=False), ] session.add_all(dags) session.commit() dag_warnings = [ DagWarning("dag_1", "non-existent pool", "non-existent pool"), DagWarning("dag_2", "non-existent pool", "non-existent pool"), ] session.add_all(dag_warnings) session.commit() DagWarning.purge_inactive_dag_warnings(session) remaining_dag_warnings = session.query(DagWarning).all() assert len(remaining_dag_warnings) == 1 assert remaining_dag_warnings[0].dag_id == "dag_2" @mock.patch("airflow.models.dagwarning.delete") def test_retry_purge_inactive_dag_warnings(self, delete_mock): """ Test that the purge_inactive_dag_warnings method calls the delete method twice if the query throws an operationalError on the first call and works on the second attempt """ self.session_mock = MagicMock() self.session_mock.execute.side_effect = [OperationalError(None, None, "database timeout"), None] DagWarning.purge_inactive_dag_warnings(self.session_mock) # Assert that the delete method was called twice assert delete_mock.call_count == 2 assert self.session_mock.execute.call_count == 2
TestDagWarning
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_oauth.py
{ "start": 103519, "end": 130339 }
class ____(TestCase): fixtures = ["eric", "test_data"] repo_response_data = { "lfs_enabled": True, "request_access_enabled": False, "approvals_before_merge": 0, "forks_count": 12, "only_allow_merge_if_all_discussions_are_resolved": False, "container_registry_enabled": True, "web_url": "https://gitlab.com/testorga/testrepo", "owner": { "username": "testorga", "web_url": "https://gitlab.com/testorga", "name": "Test Orga", "state": "active", "avatar_url": "https://secure.gravatar.com/avatar/test", "id": 42, }, "wiki_enabled": True, "id": 42, "merge_requests_enabled": True, "archived": False, "snippets_enabled": True, "http_url_to_repo": "https://gitlab.com/testorga/testrepo.git", "namespace": { "kind": "user", "name": "Test Orga", "parent_id": None, "plan": "early_adopter", "path": "testorga", "id": 42, "full_path": "testorga", }, "star_count": 1, "_links": { "repo_branches": "http://gitlab.com/api/v4/projects/42/repository/branches", "merge_requests": "http://gitlab.com/api/v4/projects/42/merge_requests", "self": "http://gitlab.com/api/v4/projects/42", "labels": "http://gitlab.com/api/v4/projects/42/labels", "members": "http://gitlab.com/api/v4/projects/42/members", "events": "http://gitlab.com/api/v4/projects/42/events", "issues": "http://gitlab.com/api/v4/projects/42/issues", }, "resolve_outdated_diff_discussions": False, "issues_enabled": True, "path_with_namespace": "testorga/testrepo", "ci_config_path": None, "shared_with_groups": [], "description": "Test Repo", "default_branch": "master", "visibility": "public", "ssh_url_to_repo": "git@gitlab.com:testorga/testrepo.git", "public_jobs": True, "path": "testrepo", "import_status": "none", "only_allow_merge_if_pipeline_succeeds": False, "open_issues_count": 0, "last_activity_at": "2017-11-28T14:21:17.570Z", "name": "testrepo", "printing_merge_request_link_enabled": True, "name_with_namespace": "testorga / testrepo", "created_at": "2017-11-27T19:19:30.906Z", "shared_runners_enabled": True, "creator_id": 389803, "avatar_url": None, "permissions": { "group_access": None, "project_access": { "notification_level": 3, "access_level": 40, }, }, "tag_list": [], "jobs_enabled": True, } group_response_data = { "id": 1, "name": "Test Orga", "path": "testorga", "description": "An interesting group", "visibility": "public", "lfs_enabled": True, "avatar_url": "https://secure.gravatar.com/avatar/test", "web_url": "https://gitlab.com/groups/testorga", "request_access_enabled": False, "full_name": "Test Orga", "full_path": "group/testorga", "parent_id": None, } def setUp(self): self.client.login(username="eric", password="test") self.user = User.objects.get(pk=1) self.project = Project.objects.get(slug="pip") self.project.repo = "https://gitlab.com/testorga/testrepo" self.project.save() self.org = RemoteOrganization.objects.create( remote_id="1", slug="testorga", vcs_provider=GITLAB, ) self.privacy = settings.DEFAULT_PRIVACY_LEVEL self.social_account = get( SocialAccount, user=self.user, provider=GitLabProvider.id, ) get( SocialToken, account=self.social_account, ) self.service = GitLabService( user=self.user, account=self.social_account ) self.external_version = get(Version, project=self.project, type=EXTERNAL) self.external_build = get( Build, project=self.project, version=self.external_version, commit=1234, ) self.integration = get( GitLabWebhook, project=self.project, provider_data={"id": "999999999"} ) self.provider_data = [ { "id": 1084320, "url": "https://readthedocs.io/api/v2/webhook/test/99999999/", } ] def get_private_repo_data(self): """Manipulate repo response data to get private repo data.""" data = self.repo_response_data.copy() data.update( { "visibility": "private", } ) return data def test_project_path_is_escaped(self): repo_id = self.service._get_repo_id(self.project) self.assertEqual(repo_id, "testorga%2Ftestrepo") self.project.repo = "https://gitlab.com/testorga/subgroup/testrepo.git" self.project.save() repo_id = self.service._get_repo_id(self.project) self.assertEqual(repo_id, "testorga%2Fsubgroup%2Ftestrepo") def test_make_project_pass(self): self.repo_response_data["namespace"] = { "kind": "group", "name": "Test Orga", "path": "testorga", "id": self.org.remote_id, "full_path": self.org.slug, } repo = self.service.create_repository(self.repo_response_data, privacy=self.privacy) self.assertIsInstance(repo, RemoteRepository) self.assertEqual(repo.name, "testrepo") self.assertEqual(repo.full_name, "testorga/testrepo") self.assertEqual(repo.remote_id, 42) self.assertEqual(repo.vcs_provider, GITLAB) self.assertEqual(repo.description, "Test Repo") self.assertEqual( repo.avatar_url, "https://secure.gravatar.com/avatar/test", ) self.assertIn(self.user, repo.users.all()) self.assertEqual(repo.organization, self.org) self.assertEqual( repo.clone_url, "https://gitlab.com/testorga/testrepo.git", ) self.assertEqual(repo.ssh_url, "git@gitlab.com:testorga/testrepo.git") self.assertEqual(repo.html_url, "https://gitlab.com/testorga/testrepo") self.assertTrue(repo.remote_repository_relations.first().admin) self.assertFalse(repo.private) def test_make_private_project_fail(self): data = self.get_private_repo_data() repo = self.service.create_repository(data, privacy=self.privacy) self.assertIsNone(repo) def test_make_private_project_success(self): data = self.get_private_repo_data() data["namespace"] = { "kind": "group", "name": "Test Orga", "path": "testorga", "id": self.org.remote_id, "full_path": self.org.slug, } repo = self.service.create_repository(data, privacy=constants.PRIVATE) self.assertIsInstance(repo, RemoteRepository) self.assertTrue(repo.private, True) def test_make_organization(self): org = self.service.create_organization(self.group_response_data) self.assertIsInstance(org, RemoteOrganization) self.assertEqual(org.slug, "group/testorga") self.assertEqual(org.name, "Test Orga") self.assertEqual( org.avatar_url, "https://secure.gravatar.com/avatar/test", ) self.assertEqual(org.url, "https://gitlab.com/groups/testorga") @override_settings(DEFAULT_PRIVACY_LEVEL="private") def test_make_private_project(self): """ Test ability to import ``public`` repositories under ``private`` level. """ data = self.repo_response_data.copy() data["visibility"] = "public" repo = self.service.create_repository(data) self.assertIsNotNone(repo) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService._get_repo_id") def test_send_build_status_successful(self, repo_id, session, mock_logger, mock_structlog): session.post.return_value.status_code = 201 repo_id().return_value = "9999" success = self.service.send_build_status( build=self.external_build, commit=self.external_build.commit, status=BUILD_STATUS_SUCCESS, ) self.assertTrue(success) mock_structlog.contextvars.bind_contextvars.assert_called_with(http_status_code=201) mock_logger.debug.assert_called_with( "GitLab commit status created for project.", ) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService._get_repo_id") def test_send_build_status_404_error(self, repo_id, session, mock_logger, mock_structlog): session.post.return_value.status_code = 404 repo_id.return_value = "9999" success = self.service.send_build_status( build=self.external_build, commit=self.external_build.commit, status=BUILD_STATUS_SUCCESS, ) self.assertFalse(success) mock_structlog.contextvars.bind_contextvars.assert_called_with(http_status_code=404) mock_logger.info.assert_called_with( "GitLab project does not exist or user does not have permissions.", ) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService._get_repo_id") def test_send_build_status_value_error(self, repo_id, session, mock_logger, mock_structlog): session.post.side_effect = ValueError repo_id().return_value = "9999" success = self.service.send_build_status( build=self.external_build, commit=self.external_build.commit, status=BUILD_STATUS_SUCCESS, ) self.assertFalse(success) mock_structlog.contextvars.bind_contextvars.assert_called_with( project_slug=self.project.slug, commit_status="success", user_username=self.user.username, url=mock.ANY, ) mock_logger.exception.assert_called_with( "GitLab commit status creation failed.", debug_data=None, ) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") def test_setup_webhook_successful(self, session, mock_logger, mock_structlog): session.post.return_value.status_code = 201 session.post.return_value.json.return_value = {} success = self.service.setup_webhook(self.project, self.integration) self.integration.refresh_from_db() self.assertTrue(success) self.assertIsNotNone(self.integration.secret) mock_structlog.contextvars.bind_contextvars.assert_called_with( http_status_code=201, ) mock_logger.debug.assert_called_with( "GitLab webhook creation successful for project.", ) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") def test_setup_webhook_404_error(self, session, mock_logger, mock_structlog): session.post.return_value.status_code = 404 success = self.service.setup_webhook(self.project, self.integration) self.integration.refresh_from_db() self.assertFalse(success) self.assertIsNotNone(self.integration.secret) mock_structlog.contextvars.bind_contextvars.assert_called_with(http_status_code=404) mock_logger.info.assert_called_with( "Gitlab project does not exist or user does not have permissions.", ) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") def test_setup_webhook_value_error(self, session, mock_logger, mock_structlog): session.post.side_effect = ValueError self.service.setup_webhook(self.project, self.integration) self.integration.refresh_from_db() self.assertIsNotNone(self.integration.secret) mock_structlog.contextvars.bind_contextvars.assert_called_with( project_slug=self.project.slug, integration_id=self.integration.pk, url="https://gitlab.com/api/v4/projects/testorga%2Ftestrepo/hooks", ) mock_logger.exception.assert_called_with( "GitLab webhook creation failed.", ) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService._get_repo_id") def test_update_webhook_successful(self, repo_id, session, mock_logger, mock_structlog): repo_id.return_value = "9999" session.put.return_value.status_code = 200 session.put.return_value.json.return_value = {} success = self.service.update_webhook(self.project, self.integration) self.integration.refresh_from_db() self.assertTrue(success) self.assertIsNotNone(self.integration.secret) mock_structlog.contextvars.bind_contextvars.assert_called_with( project_slug=self.project.slug, integration_id=self.integration.pk, ) mock_logger.info.assert_called_with( "GitLab webhook update successful for project.", ) @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.setup_webhook") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService._get_repo_id") def test_update_webhook_404_error(self, repo_id, setup_webhook, session): repo_id.return_value = "9999" session.put.return_value.status_code = 404 self.service.update_webhook(self.project, self.integration) setup_webhook.assert_called_once_with(self.project, self.integration) @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.setup_webhook") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService._get_repo_id") def test_update_webhook_no_provider_data(self, repo_id, setup_webhook, session): self.integration.provider_data = {} self.integration.save() repo_id.return_value = "9999" session.put.side_effect = AttributeError self.service.update_webhook(self.project, self.integration) setup_webhook.assert_called_once_with(self.project, self.integration) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService._get_repo_id") def test_update_webhook_value_error(self, repo_id, session, mock_logger, mock_structlog): repo_id.return_value = "9999" session.put.side_effect = ValueError self.service.update_webhook(self.project, self.integration) self.integration.refresh_from_db() self.assertIsNotNone(self.integration.secret) mock_structlog.contextvars.bind_contextvars.assert_called_with( project_slug=self.project.slug, integration_id=self.integration.pk, ) mock_logger.exception.assert_called_with( "GitLab webhook update failed.", debug_data=None, ) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") def test_get_provider_data_successful(self, session, mock_logger, mock_structlog): self.integration.provider_data = {} self.integration.save() webhook_data = self.provider_data rtd_webhook_url = "https://{domain}{path}".format( domain=settings.PRODUCTION_DOMAIN, path=reverse( "api_webhook", kwargs={ "project_slug": self.project.slug, "integration_pk": self.integration.pk, }, ), ) webhook_data[0]["url"] = rtd_webhook_url session.get.return_value.status_code = 200 session.get.return_value.json.return_value = webhook_data self.service.get_provider_data(self.project, self.integration) self.integration.refresh_from_db() self.assertEqual(self.integration.provider_data, webhook_data[0]) mock_structlog.contextvars.bind_contextvars.assert_called_with( project_slug=self.project.slug, integration_id=self.integration.pk, ) mock_logger.info.assert_called_with( "GitLab integration updated with provider data for project.", ) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") def test_get_provider_data_404_error(self, session, mock_logger, mock_structlog): self.integration.provider_data = {} self.integration.save() session.get.return_value.status_code = 404 self.service.get_provider_data(self.project, self.integration) self.integration.refresh_from_db() self.assertEqual(self.integration.provider_data, {}) mock_structlog.contextvars.bind_contextvars.assert_called_with( project_slug=self.project.slug, integration_id=self.integration.pk, ) mock_logger.info.assert_called_with( "GitLab project does not exist or user does not have permissions.", ) @mock.patch("readthedocs.oauth.services.gitlab.structlog") @mock.patch("readthedocs.oauth.services.gitlab.log") @mock.patch("readthedocs.oauth.services.gitlab.GitLabService.session") def test_get_provider_data_attribute_error(self, session, mock_logger, mock_structlog): self.integration.provider_data = {} self.integration.save() session.get.side_effect = AttributeError self.service.get_provider_data(self.project, self.integration) self.integration.refresh_from_db() self.assertEqual(self.integration.provider_data, {}) mock_structlog.contextvars.bind_contextvars.assert_called_with( project_slug=self.project.slug, integration_id=self.integration.pk, ) mock_logger.exception.assert_called_with( "GitLab webhook Listing failed for project.", ) def test_project_moved_from_user_to_group(self): repo = self.service.create_repository(self.repo_response_data) assert repo.organization is None assert repo.full_name == "testorga/testrepo" assert not repo.private assert repo.remote_repository_relations.count() == 1 relationship = repo.remote_repository_relations.first() assert relationship.admin assert relationship.user == self.user assert relationship.account == self.service.account self.repo_response_data["namespace"] = { "kind": "group", "name": "Test Orga", "path": "testorga", "id": self.org.remote_id, "full_path": self.org.slug, } repo_b = self.service.create_repository(self.repo_response_data) assert repo_b == repo repo.refresh_from_db() assert repo.organization == self.org relationship = repo.remote_repository_relations.first() assert relationship.admin assert relationship.user == self.user assert relationship.account == self.service.account def test_project_moved_from_group_to_user(self): self.repo_response_data["namespace"] = { "kind": "group", "name": "Test Orga", "path": "testorga", "id": self.org.remote_id, "full_path": self.org.slug, } repo = self.service.create_repository(self.repo_response_data) assert repo.organization == self.org assert repo.full_name == "testorga/testrepo" assert not repo.private assert repo.remote_repository_relations.count() == 1 relationship = repo.remote_repository_relations.first() assert relationship.admin assert relationship.user == self.user assert relationship.account == self.service.account self.repo_response_data["namespace"] = { "kind": "user", "name": "Test User", "path": "testuser", "id": 1, "full_path": "testuser", } repo_b = self.service.create_repository(self.repo_response_data) assert repo_b == repo repo.refresh_from_db() assert repo.organization is None relationship = repo.remote_repository_relations.first() assert relationship.admin assert relationship.user == self.user assert relationship.account == self.service.account def test_project_moved_between_groups(self): self.repo_response_data["namespace"] = { "kind": "group", "name": "Test Orga", "path": "testorga", "id": self.org.remote_id, "full_path": self.org.slug, } repo = self.service.create_repository(self.repo_response_data) assert repo.organization == self.org assert repo.full_name == "testorga/testrepo" assert not repo.private assert repo.remote_repository_relations.count() == 1 relationship = repo.remote_repository_relations.first() assert relationship.admin assert relationship.user == self.user assert relationship.account == self.service.account self.repo_response_data["namespace"] = { "kind": "group", "name": "Another Group", "path": "anothergroup", "id": "2", "full_path": "anothergroup", } repo_b = self.service.create_repository(self.repo_response_data) assert repo_b == repo repo.refresh_from_db() another_group = RemoteOrganization.objects.get( remote_id="2", vcs_provider=GITLAB, ) assert repo.organization == another_group relationship = repo.remote_repository_relations.first() assert relationship.admin assert relationship.user == self.user assert relationship.account == self.service.account @requests_mock.Mocker(kw="request") def test_update_remote_repository_gl(self, request): remote_repo = get( RemoteRepository, vcs_provider=GITLAB, full_name="testorga/testrepo", remote_id=self.repo_response_data["id"], ) assert not remote_repo.users.filter(id=self.user.id).exists() request.get(f"https://gitlab.com/api/v4/projects/{remote_repo.remote_id}", json=self.repo_response_data) self.service.update_repository(remote_repo) remote_repo.refresh_from_db() assert remote_repo.name == "testrepo" assert remote_repo.full_name == "testorga/testrepo" assert remote_repo.description == "Test Repo" assert remote_repo.users.filter(id=self.user.id).exists() relation = remote_repo.remote_repository_relations.get(user=self.user) assert relation.account == self.social_account assert relation.admin @requests_mock.Mocker(kw="request") def test_update_remote_repository_remove_user_relation(self, request): remote_repo = get( RemoteRepository, vcs_provider=GITLAB, full_name="testorga/testrepo", remote_id=self.repo_response_data["id"], ) get( RemoteRepositoryRelation, user=self.user, account=self.social_account, remote_repository=remote_repo, admin=True, ) assert remote_repo.users.filter(id=self.user.id).exists() request.get(f"https://gitlab.com/api/v4/projects/{remote_repo.remote_id}", status_code=404) self.service.update_repository(remote_repo) remote_repo.refresh_from_db() assert remote_repo.full_name == "testorga/testrepo" assert not remote_repo.description assert not remote_repo.users.filter(id=self.user.id).exists() @requests_mock.Mocker(kw="request") def test_update_remote_repository_remove_user_relation_public_repo(self, request): remote_repo = get( RemoteRepository, vcs_provider=GITLAB, full_name="testorga/testrepo", remote_id=self.repo_response_data["id"], ) get( RemoteRepositoryRelation, user=self.user, account=self.social_account, remote_repository=remote_repo, admin=True, ) assert remote_repo.users.filter(id=self.user.id).exists() for k in self.repo_response_data["permissions"]: self.repo_response_data["permissions"][k] = None request.get(f"https://gitlab.com/api/v4/projects/{remote_repo.remote_id}", json=self.repo_response_data) self.service.update_repository(remote_repo) remote_repo.refresh_from_db() assert remote_repo.name == "testrepo" assert remote_repo.full_name == "testorga/testrepo" assert remote_repo.description == "Test Repo" assert not remote_repo.users.filter(id=self.user.id).exists()
GitLabOAuthTests
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/scatter_ops_test.py
{ "start": 3624, "end": 12211 }
class ____(test.TestCase): def _VariableRankTest(self, tf_scatter, vtype, itype, repeat_indices=False, updates_are_scalar=False): np.random.seed(8) with self.cached_session(): for indices_shape in (), (2,), (3, 7), (3, 4, 7): for extra_shape in (), (5,), (5, 9): # Generate random indices with no duplicates for easy numpy comparison size = np.prod(indices_shape, dtype=itype) first_dim = 3 * size indices = np.arange(first_dim) np.random.shuffle(indices) indices = indices[:size] if size > 1 and repeat_indices: # Add some random repeats. indices = indices[:size // 2] for _ in range(size - size // 2): # Randomly append some repeats. indices = np.append(indices, indices[np.random.randint(size // 2)]) np.random.shuffle(indices) indices = indices.reshape(indices_shape) if updates_are_scalar: updates = _AsType(np.random.randn(), vtype) else: updates = _AsType( np.random.randn(*(indices_shape + extra_shape)), vtype) # Clips small values to avoid division by zero. threshold = np.array(1e-4, dtype=vtype) sign = np.sign(updates) if vtype == np.int32: threshold = 1 sign = np.random.choice([-1, 1], updates.shape) updates = np.where( np.abs(updates) < threshold, threshold * sign, updates) old = _AsType(np.random.randn(*((first_dim,) + extra_shape)), vtype) # Scatter via numpy new = old.copy() if updates_are_scalar: np_scatter = _TF_OPS_TO_NUMPY_SCALAR[tf_scatter] else: np_scatter = _TF_OPS_TO_NUMPY[tf_scatter] np_scatter(new, indices, updates) # Scatter via tensorflow ref = variables.Variable(old) self.evaluate(ref.initializer) self.evaluate(tf_scatter(ref, indices, updates)) self.assertAllCloseAccordingToType( self.evaluate(ref), new, half_rtol=5e-3, half_atol=5e-3, bfloat16_rtol=5e-2, bfloat16_atol=5e-2) def _VariableRankTests(self, tf_scatter, repeat_indices=False, updates_are_scalar=False): vtypes = [np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype] if tf_scatter != state_ops.scatter_div: vtypes.append(np.int32) # float16 is numerically unstable for div vtypes.append(np.float16) for vtype in vtypes: for itype in (np.int32, np.int64): self._VariableRankTest(tf_scatter, vtype, itype, repeat_indices, updates_are_scalar) def testVariableRankUpdate(self): self._VariableRankTests(state_ops.scatter_update, False) def testVariableRankAdd(self): self._VariableRankTests(state_ops.scatter_add, False) def testVariableRankSub(self): self._VariableRankTests(state_ops.scatter_sub, False) def testVariableRankMul(self): self._VariableRankTests(state_ops.scatter_mul, False) def testVariableRankDiv(self): self._VariableRankTests(state_ops.scatter_div, False) def testVariableRankMin(self): self._VariableRankTests(state_ops.scatter_min, False) def testVariableRankMax(self): self._VariableRankTests(state_ops.scatter_max, False) def testRepeatIndicesAdd(self): self._VariableRankTests(state_ops.scatter_add, True) def testRepeatIndicesSub(self): self._VariableRankTests(state_ops.scatter_sub, True) def testRepeatIndicesMul(self): self._VariableRankTests(state_ops.scatter_mul, True) def testRepeatIndicesDiv(self): self._VariableRankTests(state_ops.scatter_div, True) def testRepeatIndicesMin(self): self._VariableRankTests(state_ops.scatter_min, True) def testRepeatIndicesMax(self): self._VariableRankTests(state_ops.scatter_max, True) def testVariableRankUpdateScalar(self): self._VariableRankTests(state_ops.scatter_update, False, True) def testVariableRankAddScalar(self): self._VariableRankTests(state_ops.scatter_add, False, True) def testVariableRankSubScalar(self): self._VariableRankTests(state_ops.scatter_sub, False, True) def testVariableRankMulScalar(self): self._VariableRankTests(state_ops.scatter_mul, False, True) def testVariableRankDivScalar(self): self._VariableRankTests(state_ops.scatter_div, False, True) def testVariableRankMinScalar(self): self._VariableRankTests(state_ops.scatter_min, False, True) def testVariableRankMaxScalar(self): self._VariableRankTests(state_ops.scatter_max, False, True) def testRepeatIndicesAddScalar(self): self._VariableRankTests(state_ops.scatter_add, True, True) def testRepeatIndicesSubScalar(self): self._VariableRankTests(state_ops.scatter_sub, True, True) def testRepeatIndicesMulScalar(self): self._VariableRankTests(state_ops.scatter_mul, True, True) def testRepeatIndicesDivScalar(self): self._VariableRankTests(state_ops.scatter_div, True, True) def testRepeatIndicesMinScalar(self): self._VariableRankTests(state_ops.scatter_min, True, True) def testRepeatIndicesMaxScalar(self): self._VariableRankTests(state_ops.scatter_max, True, True) def testBooleanScatterUpdate(self): if not test.is_gpu_available(): with self.session(use_gpu=False): var = variables.Variable([True, False]) update0 = state_ops.scatter_update(var, 1, True) update1 = state_ops.scatter_update( var, constant_op.constant( 0, dtype=dtypes.int64), False) self.evaluate(var.initializer) self.evaluate([update0, update1]) self.assertAllEqual([False, True], self.evaluate(var)) def testScatterOutOfRangeCpu(self): for op, _ in _TF_OPS_TO_NUMPY.items(): params = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32) updates = np.array([-3, -4, -5]).astype(np.float32) if not test.is_gpu_available(): with self.session(use_gpu=False): ref = variables.Variable(params) self.evaluate(ref.initializer) # Indices all in range, no problem. indices = np.array([2, 0, 5]) self.evaluate(op(ref, indices, updates)) # Test some out of range errors. indices = np.array([-1, 0, 5]) with self.assertRaisesOpError( r'indices\[0\] = -1 is not in \[0, 6\)'): self.evaluate(op(ref, indices, updates)) indices = np.array([2, 0, 6]) with self.assertRaisesOpError(r'indices\[2\] = 6 is not in \[0, 6\)'): self.evaluate(op(ref, indices, updates)) # TODO(fpmc): Re-enable this test when gpu_pip test actually runs on a GPU. def _disabledTestScatterOutOfRangeGpu(self): if test.is_gpu_available(): return for op, _ in _TF_OPS_TO_NUMPY.items(): params = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32) updates = np.array([-3, -4, -5]).astype(np.float32) # With GPU, the code ignores indices that are out of range. # We don't test the implementation; just test there's no failures. with test_util.force_gpu(): ref = variables.Variable(params) self.evaluate(ref.initializer) # Indices all in range, no problem. indices = np.array([2, 0, 5]) self.evaluate(op(ref, indices, updates)) # Indices out of range should not fail. indices = np.array([-1, 0, 5]) self.evaluate(op(ref, indices, updates)) indices = np.array([2, 0, 6]) self.evaluate(op(ref, indices, updates)) @test_util.run_v1_only("ResrouceVariable has deterministic scatter " "implementation") @test_util.run_cuda_only def testDeterminismExceptionThrowing(self): v = ref_variable.RefVariable(np.array([1., 2., 3.])) indices = np.array([0, 0, 0]) updates = np.array([-3, -4, -5]).astype(np.float32) with test_util.deterministic_ops(): with self.assertRaisesRegex( errors.UnimplementedError, "Determinism is not yet supported in GPU implementation of Scatter " "ops"): self.evaluate(state_ops.scatter_update(v, indices, updates)) if __name__ == '__main__': test.main()
ScatterTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/paramSpec27.py
{ "start": 1252, "end": 1659 }
class ____(Generic[P]): def __init__(self, handler: Handler[P]) -> None: self.handler: Handler[P] = handler commands: list[Command[...]] = [] def do_something(int_handler: Handler[int], var_args_handler: Handler[P], /) -> None: int_command = Command(int_handler) commands.append(int_command) var_args_command = Command(var_args_handler) commands.append(var_args_command)
Command
python
walkccc__LeetCode
solutions/2735. Collecting Chocolates/2735.py
{ "start": 0, "end": 380 }
class ____: def minCost(self, nums: list[int], x: int) -> int: n = len(nums) ans = math.inf # minCost[i] := the minimum cost to collect the i-th type minCost = [math.inf] * n for rotate in range(n): for i in range(n): minCost[i] = min(minCost[i], nums[(i - rotate + n) % n]) ans = min(ans, sum(minCost) + rotate * x) return ans
Solution
python
scipy__scipy
scipy/spatial/tests/test_kdtree.py
{ "start": 16264, "end": 16427 }
class ____(_Test_two_random_trees_periodic): def setup_method(self): super().setup_method() self.p = np.inf
_Test_two_random_trees_linf_periodic
python
openai__openai-python
src/openai/resources/models.py
{ "start": 10823, "end": 11232 }
class ____: def __init__(self, models: AsyncModels) -> None: self._models = models self.retrieve = async_to_streamed_response_wrapper( models.retrieve, ) self.list = async_to_streamed_response_wrapper( models.list, ) self.delete = async_to_streamed_response_wrapper( models.delete, )
AsyncModelsWithStreamingResponse
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 334380, "end": 334603 }
class ____(IRNode): @cache_on_self_and_args("NonTensorObj") def get_free_symbol_uses( self, unbacked_only: bool = False ) -> OrderedSet[sympy.Symbol]: return OrderedSet() @ir_dataclass
NonTensorObj
python
PyCQA__pylint
pylint/checkers/strings.py
{ "start": 8712, "end": 25959 }
class ____(BaseChecker): """Checks string formatting operations to ensure that the format string is valid and the arguments match the format string. """ name = "string" msgs = MSGS # pylint: disable = too-many-branches, too-many-locals, too-many-statements @only_required_for_messages( "bad-format-character", "truncated-format-string", "mixed-format-string", "bad-format-string-key", "missing-format-string-key", "unused-format-string-key", "bad-string-format-type", "format-needs-mapping", "too-many-format-args", "too-few-format-args", "format-string-without-interpolation", ) def visit_binop(self, node: nodes.BinOp) -> None: if node.op != "%": return left = node.left args = node.right if not (isinstance(left, nodes.Const) and isinstance(left.value, str)): return format_string = left.value try: ( required_keys, required_num_args, required_key_types, required_arg_types, ) = utils.parse_format_string(format_string) except utils.UnsupportedFormatCharacter as exc: formatted = format_string[exc.index] self.add_message( "bad-format-character", node=node, args=(formatted, ord(formatted), exc.index), ) return except utils.IncompleteFormatString: self.add_message("truncated-format-string", node=node) return if not required_keys and not required_num_args: self.add_message("format-string-without-interpolation", node=node) return if required_keys and required_num_args: # The format string uses both named and unnamed format # specifiers. self.add_message("mixed-format-string", node=node) elif required_keys: # The format string uses only named format specifiers. # Check that the RHS of the % operator is a mapping object # that contains precisely the set of keys required by the # format string. if isinstance(args, nodes.Dict): keys = set() unknown_keys = False for k, _ in args.items: if isinstance(k, nodes.Const): key = k.value if isinstance(key, str): keys.add(key) else: self.add_message( "bad-format-string-key", node=node, args=key ) else: # One of the keys was something other than a # constant. Since we can't tell what it is, # suppress checks for missing keys in the # dictionary. unknown_keys = True if not unknown_keys: for key in required_keys: if key not in keys: self.add_message( "missing-format-string-key", node=node, args=key ) for key in keys: if key not in required_keys: self.add_message( "unused-format-string-key", node=node, args=key ) for key, arg in args.items: if not isinstance(key, nodes.Const): continue format_type = required_key_types.get(key.value, None) arg_type = utils.safe_infer(arg) if ( format_type is not None and arg_type and not isinstance(arg_type, util.UninferableBase) and not arg_matches_format_type(arg_type, format_type) ): self.add_message( "bad-string-format-type", node=node, args=(arg_type.pytype(), format_type), ) elif isinstance(args, (OTHER_NODES, nodes.Tuple)): type_name = type(args).__name__ self.add_message("format-needs-mapping", node=node, args=type_name) # else: # The RHS of the format specifier is a name or # expression. It may be a mapping object, so # there's nothing we can check. else: # The format string uses only unnamed format specifiers. # Check that the number of arguments passed to the RHS of # the % operator matches the number required by the format # string. args_elts = [] if isinstance(args, nodes.Tuple): rhs_tuple = utils.safe_infer(args) num_args = None if isinstance(rhs_tuple, nodes.BaseContainer): args_elts = rhs_tuple.elts num_args = len(args_elts) elif isinstance(args, (OTHER_NODES, (nodes.Dict, nodes.DictComp))): args_elts = [args] num_args = 1 elif isinstance(args, nodes.Name): inferred = utils.safe_infer(args) if isinstance(inferred, nodes.Tuple): # The variable is a tuple, so we need to get the elements # from it for further inspection args_elts = inferred.elts num_args = len(args_elts) elif isinstance(inferred, nodes.Const): args_elts = [inferred] num_args = 1 else: num_args = None else: # The RHS of the format specifier is an expression. # It could be a tuple of unknown size, so # there's nothing we can check. num_args = None if num_args is not None: if num_args > required_num_args: self.add_message("too-many-format-args", node=node) elif num_args < required_num_args: self.add_message("too-few-format-args", node=node) for arg, format_type in zip(args_elts, required_arg_types): if not arg: continue arg_type = utils.safe_infer(arg) if ( arg_type and not isinstance(arg_type, util.UninferableBase) and not arg_matches_format_type(arg_type, format_type) ): self.add_message( "bad-string-format-type", node=node, args=(arg_type.pytype(), format_type), ) @only_required_for_messages("f-string-without-interpolation") def visit_joinedstr(self, node: nodes.JoinedStr) -> None: self._check_interpolation(node) def _check_interpolation(self, node: nodes.JoinedStr) -> None: if isinstance(node.parent, (nodes.TemplateStr, nodes.FormattedValue)): return for value in node.values: if isinstance(value, nodes.FormattedValue): return self.add_message("f-string-without-interpolation", node=node) def visit_call(self, node: nodes.Call) -> None: match func := utils.safe_infer(node.func): case astroid.BoundMethod( bound=astroid.Instance(name="str" | "unicode" | "bytes" as bound_name), ): if func.name in {"strip", "lstrip", "rstrip"} and node.args: arg = utils.safe_infer(node.args[0]) if not ( isinstance(arg, nodes.Const) and isinstance(arg.value, str) ): return if len(arg.value) != len(set(arg.value)): self.add_message( "bad-str-strip-call", node=node, args=(bound_name, func.name), ) elif func.name == "format": self._check_new_format(node, func) def _detect_vacuous_formatting( self, node: nodes.Call, positional_arguments: list[SuccessfulInferenceResult] ) -> None: counter = collections.Counter( arg.name for arg in positional_arguments if isinstance(arg, nodes.Name) ) for name, count in counter.items(): if count == 1: continue self.add_message( "duplicate-string-formatting-argument", node=node, args=(name,) ) def _check_new_format(self, node: nodes.Call, func: bases.BoundMethod) -> None: """Check the new string formatting.""" # Skip format nodes which don't have an explicit string on the # left side of the format operation. # We do this because our inference engine can't properly handle # redefinition of the original string. # Note that there may not be any left side at all, if the format method # has been assigned to another variable. See issue 351. For example: # # fmt = 'some string {}'.format # fmt('arg') if isinstance(node.func, nodes.Attribute) and not isinstance( node.func.expr, nodes.Const ): return if node.starargs or node.kwargs: return try: strnode = next(func.bound.infer()) except astroid.InferenceError: return if not (isinstance(strnode, nodes.Const) and isinstance(strnode.value, str)): return try: call_site = arguments.CallSite.from_call(node) except astroid.InferenceError: return try: fields, num_args, manual_pos = utils.parse_format_method_string( strnode.value ) except utils.IncompleteFormatString: self.add_message("bad-format-string", node=node) return positional_arguments = call_site.positional_arguments named_arguments = call_site.keyword_arguments named_fields = {field[0] for field in fields if isinstance(field[0], str)} if num_args and manual_pos: self.add_message("format-combined-specification", node=node) return check_args = False # Consider "{[0]} {[1]}" as num_args. num_args += sum(1 for field in named_fields if not field) if named_fields: for field in named_fields: if field and field not in named_arguments: self.add_message( "missing-format-argument-key", node=node, args=(field,) ) for field in named_arguments: if field not in named_fields: self.add_message( "unused-format-string-argument", node=node, args=(field,) ) # num_args can be 0 if manual_pos is not. num_args = num_args or manual_pos if positional_arguments or num_args: empty = not all(field for field in named_fields) if named_arguments or empty: # Verify the required number of positional arguments # only if the .format got at least one keyword argument. # This means that the format strings accepts both # positional and named fields and we should warn # when one of them is missing or is extra. check_args = True else: check_args = True if check_args: # num_args can be 0 if manual_pos is not. num_args = num_args or manual_pos if not num_args: self.add_message("format-string-without-interpolation", node=node) return if len(positional_arguments) > num_args: self.add_message("too-many-format-args", node=node) elif len(positional_arguments) < num_args: self.add_message("too-few-format-args", node=node) self._detect_vacuous_formatting(node, positional_arguments) self._check_new_format_specifiers(node, fields, named_arguments) # pylint: disable = too-many-statements def _check_new_format_specifiers( self, node: nodes.Call, fields: list[tuple[str, list[tuple[bool, str]]]], named: dict[str, SuccessfulInferenceResult], ) -> None: """Check attribute and index access in the format string ("{0.a}" and "{0[a]}"). """ key: Literal[0] | str for key, specifiers in fields: # Obtain the argument. If it can't be obtained # or inferred, skip this check. if not key: # {[0]} will have an unnamed argument, defaulting # to 0. It will not be present in `named`, so use the value # 0 for it. key = 0 if isinstance(key, int): try: argname = utils.get_argument_from_call(node, key) except utils.NoSuchArgumentError: continue else: if key not in named: continue argname = named[key] if argname is None or isinstance(argname, util.UninferableBase): continue try: argument = utils.safe_infer(argname) except astroid.InferenceError: continue if not (specifiers and argument): # No need to check this key if it doesn't # use attribute / item access continue if argument.parent and isinstance(argument.parent, nodes.Arguments): # Ignore any object coming from an argument, # because we can't infer its value properly. continue previous = argument parsed: list[tuple[bool, str]] = [] for is_attribute, specifier in specifiers: if isinstance(previous, util.UninferableBase): break parsed.append((is_attribute, specifier)) if is_attribute: try: previous = previous.getattr(specifier)[0] except astroid.NotFoundError: if ( hasattr(previous, "has_dynamic_getattr") and previous.has_dynamic_getattr() ): # Don't warn if the object has a custom __getattr__ break path = get_access_path(key, parsed) self.add_message( "missing-format-attribute", args=(specifier, path), node=node, ) break else: warn_error = False if hasattr(previous, "getitem"): try: previous = previous.getitem(nodes.Const(specifier)) except ( astroid.AstroidIndexError, astroid.AstroidTypeError, astroid.AttributeInferenceError, ): warn_error = True except astroid.InferenceError: break if isinstance(previous, util.UninferableBase): break else: try: # Lookup __getitem__ in the current node, # but skip further checks, because we can't # retrieve the looked object previous.getattr("__getitem__") break except astroid.NotFoundError: warn_error = True if warn_error: path = get_access_path(key, parsed) self.add_message( "invalid-format-index", args=(specifier, path), node=node ) break try: previous = next(previous.infer()) except astroid.InferenceError: # can't check further if we can't infer it break
StringFormatChecker
python
astropy__astropy
docs/wcs/examples/planetary_wcs.py
{ "start": 205, "end": 359 }
class ____(BaseBodycentricRepresentation): _equatorial_radius = 3399190.0 * u.m _flattening = 0.5886 * u.percent
MARSCustomBodycentricRepresentation
python
ApeWorX__ape
src/ape/api/query.py
{ "start": 7242, "end": 7577 }
class ____(_BaseBlockQuery): """ A ``QueryType`` that collects members from ``event`` over a range of logs emitted by ``contract`` between ``start_block`` and ``stop_block``. """ contract: Union[list[AddressType], AddressType] event: EventABI search_topics: Optional[dict[str, Any]] = None
ContractEventQuery
python
spack__spack
lib/spack/spack/test/oci/urlopen.py
{ "start": 9762, "end": 12369 }
class ____(DummyServer): """A trivial auth server that hands out a bearer token at GET /login.""" def __init__(self, domain: str, token: str) -> None: super().__init__(domain) self.router.register("GET", "/login", self.login) self.token = token def login(self, req: Request): return MockHTTPResponse.with_json(200, "OK", body={"token": self.token}) def test_registry_with_short_lived_bearer_tokens(): """An issued bearer token is mostly opaque to the client, but typically it embeds a short-lived expiration date. To speed up requests to a registry, it's good not to authenticate on every request, but to cache the bearer token, however: we have to deal with the case of an expired bearer token. Here we test that when the bearer token expires, we authenticate again, and when the token is still valid, we don't re-authenticate.""" image = ImageReference.from_string("private.example.com/image") credentials_provider = lambda domain: UsernamePassword("user", "pass") auth_server = TrivialAuthServer("auth.example.com", token="token") registry_server = InMemoryOCIRegistryWithBearerAuth( image.domain, token="token", realm="https://auth.example.com/login" ) urlopen = create_opener( registry_server, auth_server, credentials_provider=credentials_provider ).open # First request, should work with token "token" assert urlopen(image.endpoint()).status == 200 # Invalidate the token on the registry registry_server.token = "new_token" auth_server.token = "new_token" # Second request: reusing the cached token should fail # but in the background we will get a new token from the auth server assert urlopen(image.endpoint()).status == 200 # Subsequent requests should work with the same token, let's do two more assert urlopen(image.endpoint()).status == 200 assert urlopen(image.endpoint()).status == 200 # And finally, we should see that we've issues exactly two requests to the auth server assert auth_server.requests == [("GET", "/login"), ("GET", "/login")] # Whereas we've done more requests to the registry assert registry_server.requests == [ ("GET", "/v2/"), # 1: without bearer token ("GET", "/v2/"), # 2: retry with bearer token ("GET", "/v2/"), # 3: with incorrect bearer token ("GET", "/v2/"), # 4: retry with new bearer token ("GET", "/v2/"), # 5: with recyled correct bearer token ("GET", "/v2/"), # 6: with recyled correct bearer token ]
TrivialAuthServer
python
sympy__sympy
sympy/codegen/rewriting.py
{ "start": 1860, "end": 2341 }
class ____: """ Abstract base class for rewriting optimization. Subclasses should implement ``__call__`` taking an expression as argument. Parameters ========== cost_function : callable returning number priority : number """ def __init__(self, cost_function=None, priority=1): self.cost_function = cost_function self.priority=priority def cheapest(self, *args): return min(args, key=self.cost_function)
Optimization
python
pytorch__pytorch
torch/distributed/fsdp/wrap.py
{ "start": 6313, "end": 7699 }
class ____(_Policy): """ This policy applies to every module of the specified module classes, passing in the kwargs given to the root. """ def __init__(self, module_classes: Iterable[type[nn.Module]]): module_classes_set = set(module_classes) self._module_classes = module_classes_set self._module_classes_str = str(module_classes_set) def _run_policy( self, root_module: nn.Module, ignored_modules: set[nn.Module], root_kwargs: dict[str, Any], ) -> dict[nn.Module, dict[str, Any]]: module_classes = tuple(self._module_classes) target_module_to_kwargs: dict[nn.Module, dict[str, Any]] = {} for module in root_module.modules(): if module in ignored_modules: continue elif isinstance(module, module_classes): # Shallow copy to avoid coupling changes across modules target_module_to_kwargs[module] = copy.copy(root_kwargs) return target_module_to_kwargs def __call__(self, module, recurse, *args, **kwargs): # nonwrapped_numel is not used. return _module_wrap_policy( module, recurse, nonwrapped_numel=-1, module_classes=self._module_classes ) def __repr__(self) -> str: return super().__repr__() + f"({self._module_classes_str})"
ModuleWrapPolicy
python
doocs__leetcode
solution/0300-0399/0341.Flatten Nested List Iterator/Solution.py
{ "start": 772, "end": 1415 }
class ____: def __init__(self, nestedList: [NestedInteger]): def dfs(ls): for x in ls: if x.isInteger(): self.nums.append(x.getInteger()) else: dfs(x.getList()) self.nums = [] self.i = -1 dfs(nestedList) def next(self) -> int: self.i += 1 return self.nums[self.i] def hasNext(self) -> bool: return self.i + 1 < len(self.nums) # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
NestedIterator
python
Netflix__metaflow
test/unit/inheritance/flows/comprehensive_multi_hierarchy_base.py
{ "start": 2124, "end": 2355 }
class ____(FlowSpec): """Second hierarchy root""" param_x = Parameter("param_x", help="Parameter X", default=30) config_x = Config( "config_x", default_value={"source": "hierarchy_x", "multiplier": 2} )
BaseX
python
apache__airflow
providers/openlineage/tests/unit/openlineage/utils/test_selective_enable.py
{ "start": 1162, "end": 3006 }
class ____: def setup_method(self): @dag(dag_id="test_selective_enable_decorated_dag", schedule=None, start_date=now()) def decorated_dag(): @task def decorated_task(): return "test" self.decorated_task = decorated_task() self.decorated_dag = decorated_dag() with DAG(dag_id="test_selective_enable_dag", schedule=None, start_date=now()) as self.dag: self.task = EmptyOperator(task_id="test_selective_enable") def test_enable_lineage_task_level(self): assert ENABLE_OL_PARAM_NAME not in self.task.params enable_lineage(self.task) assert ENABLE_OL_PARAM.value == self.task.params[ENABLE_OL_PARAM_NAME] def test_disable_lineage_task_level(self): assert ENABLE_OL_PARAM_NAME not in self.task.params disable_lineage(self.task) assert DISABLE_OL_PARAM.value == self.task.params[ENABLE_OL_PARAM_NAME] def test_enable_lineage_dag_level(self): assert ENABLE_OL_PARAM_NAME not in self.dag.params enable_lineage(self.dag) assert ENABLE_OL_PARAM.value == self.dag.params[ENABLE_OL_PARAM_NAME] # check if param propagates to the task assert ENABLE_OL_PARAM.value == self.task.params[ENABLE_OL_PARAM_NAME] def test_enable_lineage_decorated_dag(self): enable_lineage(self.decorated_dag) assert ENABLE_OL_PARAM.value == self.decorated_dag.params[ENABLE_OL_PARAM_NAME] # check if param propagates to the task assert ENABLE_OL_PARAM.value == self.decorated_task.operator.params[ENABLE_OL_PARAM_NAME] def test_enable_lineage_decorated_task(self): enable_lineage(self.decorated_task) assert ENABLE_OL_PARAM.value == self.decorated_task.operator.params[ENABLE_OL_PARAM_NAME]
TestOpenLineageSelectiveEnable
python
ZoranPandovski__al-go-rithms
stats.py
{ "start": 2081, "end": 3685 }
class ____: """Calculates some metric on the given repository. The calculated data is stores as JSON in the given JsonStore. Once the metric data is calculated and stored, a badge would be generated with the calculated values. Params: store - the JsonStore in which to store the metric data. badge_generator - function to generate the badge data. The badge_calculator signature looks like this: def badge_calculator(value): return { 'provider': 'string, the name of the badge provider', 'url': 'string, the URL of the badge image', 'markup': 'string, generated markup to use in documents' } """ def __init__(self, store, badge_generator): self.store = store self.badge_generator = badge_generator def calculate(self): """Calculates the metrics data, then stores and generates the badge. """ value = self.do_calculate() self.store.save(value) value['data_url'] = self.store.get_url() self.badge_generated(self.badge_generator(value)) @abstractmethod def do_calculate(self): """Performs the actual calculation of the metric data. The return result must be a dict containing 'data_url' - URL to the remote JSON data from the store. """ pass @abstractmethod def badge_generated(self, badge): """Called after the metric data has been calculated and the badge data is generated. """ pass
Metric
python
django__django
django/db/migrations/operations/models.py
{ "start": 26142, "end": 26463 }
class ____(AlterTogetherOptionOperation): """ Change the value of index_together to the target one. Input value of index_together must be a set of tuples. """ option_name = "index_together" def __init__(self, name, index_together): super().__init__(name, index_together)
AlterIndexTogether
python
PrefectHQ__prefect
tests/server/models/test_work_queues.py
{ "start": 2705, "end": 3242 }
class ____: async def test_read_work_queue_by_name(self, session, work_queue): read_work_queue = await models.work_queues.read_work_queue_by_name( session=session, name=work_queue.name ) assert read_work_queue.id == work_queue.id async def test_read_work_queue_by_name_returns_none_if_does_not_exist( self, session ): assert not await models.work_queues.read_work_queue_by_name( session=session, name="a name that doesn't exist" )
TestReadWorkQueueByName
python
tornadoweb__tornado
tornado/test/util_test.py
{ "start": 8793, "end": 9001 }
class ____(unittest.TestCase): def test_timedelta_to_seconds(self): time_delta = datetime.timedelta(hours=1) self.assertEqual(timedelta_to_seconds(time_delta), 3600.0)
TimedeltaToSecondsTest
python
google__pytype
pytype/types/functions.py
{ "start": 2247, "end": 2514 }
class ____(base.BaseValue): """Base class for representation of python functions.""" is_overload: bool name: str decorators: list[str] def signatures(self) -> list[Signature]: """All signatures of this function.""" raise NotImplementedError()
Function
python
weaviate__weaviate-python-client
weaviate/gql/filter.py
{ "start": 17580, "end": 19883 }
class ____(Filter): """Sort filter class used to sort weaviate objects.""" def __init__(self, content: Union[dict, list]): """Initialize a Where filter class instance. Args: content: The content of the `sort` filter clause or a single clause. Raises: TypeError: If 'content' is not of type dict. ValueError: If a mandatory key is missing in the filter content. """ # content is a empty list because it is going to the the list with sort clauses. super().__init__(content={"sort": []}) self.add(content=content) def add(self, content: Union[dict, list]) -> None: """Add more sort clauses to the already existing sort clauses. Args: content: The content of the `sort` filter clause or a single clause to be added to the already existing ones. Raises: TypeError: If 'content' is not of type dict. ValueError: If a mandatory key is missing in the filter content. """ if isinstance(content, dict): content = [content] if not isinstance(content, list): raise TypeError(f"'content' must be of type dict or list. Given type: {type(content)}.") if len(content) == 0: raise ValueError("'content' cannot be an empty list.") for clause in content: if "path" not in clause or "order" not in clause: raise ValueError( "One of the sort clause is missing required fields: 'path' and/or 'order'." ) _check_type( var_name="path", value=clause["path"], dtype=list, ) _check_type( var_name="order", value=clause["order"], dtype=str, ) self._content["sort"].append( { "path": clause["path"], "order": clause["order"], } ) def __str__(self) -> str: sort = "sort: [" for clause in self._content["sort"]: sort += f"{{ path: {dumps(clause['path'])} order: {clause['order']} }} " sort += "]" return sort
Sort
python
cython__cython
Cython/Tests/TestStringIOTree.py
{ "start": 351, "end": 1946 }
class ____(unittest.TestCase): def setUp(self): self.tree = stringtree.StringIOTree() def test_markers(self): assert not self.tree.allmarkers() def test_insertion(self): self.write_lines((1, 2, 3)) line_4_to_6_insertion_point = self.tree.insertion_point() self.write_lines((7, 8)) line_9_to_13_insertion_point = self.tree.insertion_point() self.write_lines((14, 15, 16)) line_4_insertion_point = line_4_to_6_insertion_point.insertion_point() self.write_lines((5, 6), tree=line_4_to_6_insertion_point) line_9_to_12_insertion_point = ( line_9_to_13_insertion_point.insertion_point()) self.write_line(13, tree=line_9_to_13_insertion_point) self.write_line(4, tree=line_4_insertion_point) self.write_line(9, tree=line_9_to_12_insertion_point) line_10_insertion_point = line_9_to_12_insertion_point.insertion_point() self.write_line(11, tree=line_9_to_12_insertion_point) self.write_line(10, tree=line_10_insertion_point) self.write_line(12, tree=line_9_to_12_insertion_point) self.assertEqual(self.tree.allmarkers(), list(range(1, 17))) self.assertEqual(code.strip(), self.tree.getvalue().strip()) def write_lines(self, linenos, tree=None): for lineno in linenos: self.write_line(lineno, tree=tree) def write_line(self, lineno, tree=None): if tree is None: tree = self.tree tree.markers.append(lineno) tree.write(linemap[lineno] + '\n')
TestStringIOTree
python
django-import-export__django-import-export
tests/core/tests/test_forms.py
{ "start": 1455, "end": 2989 }
class ____(TestCase): def test_import_form_media(self): form = forms.ImportForm([CSV], [MyResource]) media = form.media self.assertEqual( media._css, {}, ) self.assertEqual( media._js, [ "admin/js/vendor/jquery/jquery.min.js", "admin/js/jquery.init.js", "import_export/guess_format.js", ], ) def test_import_form_and_custom_widget_media(self): class TestMediaWidget(django.forms.TextInput): """Dummy test widget with associated CSS and JS media.""" class Media: css = { "all": ["test.css"], } js = ["test.js"] class CustomImportForm(forms.ImportForm): """Dummy custom import form with a custom widget.""" author = django.forms.ModelChoiceField( queryset=Author.objects.none(), required=True, widget=TestMediaWidget, ) form = CustomImportForm([CSV], [MyResource]) media = form.media self.assertEqual( media._css, {"all": ["test.css"]}, ) self.assertEqual( media._js, [ "test.js", "admin/js/vendor/jquery/jquery.min.js", "admin/js/jquery.init.js", "import_export/guess_format.js", ], )
ImportFormMediaTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 648661, "end": 649436 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "cursor", "member_access_resource_path", "member_access_url", "node", "role", ) cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") member_access_resource_path = sgqlc.types.Field( sgqlc.types.non_null(URI), graphql_name="memberAccessResourcePath" ) member_access_url = sgqlc.types.Field( sgqlc.types.non_null(URI), graphql_name="memberAccessUrl" ) node = sgqlc.types.Field(sgqlc.types.non_null("User"), graphql_name="node") role = sgqlc.types.Field(sgqlc.types.non_null(TeamMemberRole), graphql_name="role")
TeamMemberEdge
python
huggingface__transformers
src/transformers/models/roformer/modeling_roformer.py
{ "start": 14985, "end": 17853 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_idx=None): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = RoFormerAttention(config, layer_idx) self.is_decoder = config.is_decoder self.add_cross_attention = config.add_cross_attention if self.add_cross_attention: if not self.is_decoder: raise ValueError(f"{self} should be used as a decoder model if cross attention is added") self.crossattention = RoFormerAttention(config, layer_idx) self.intermediate = RoFormerIntermediate(config) self.output = RoFormerOutput(config) def forward( self, hidden_states, attention_mask=None, sinusoidal_pos=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, output_attentions=False, cache_position=None, ): self_attention_outputs = self.attention( hidden_states, attention_mask=attention_mask, sinusoidal_pos=sinusoidal_pos, output_attentions=output_attentions, past_key_values=past_key_values, cache_position=cache_position, ) attention_output = self_attention_outputs[0] outputs = self_attention_outputs[1:] # add self attentions if we output attention weights if self.is_decoder and encoder_hidden_states is not None: if not hasattr(self, "crossattention"): raise ValueError( f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention " "layers by setting `config.add_cross_attention=True`" ) cross_attention_outputs = self.crossattention( attention_output, attention_mask=encoder_attention_mask, sinusoidal_pos=sinusoidal_pos, encoder_hidden_states=encoder_hidden_states, past_key_values=past_key_values, output_attentions=output_attentions, cache_position=cache_position, ) attention_output = cross_attention_outputs[0] outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output ) return (layer_output,) + outputs def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output
RoFormerLayer
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_not_holiday.py
{ "start": 2118, "end": 5063 }
class ____(ColumnMapExpectation): """Expect the provided dates are not holiday in the given country (in parameter).""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "all_not_holiday": [ "2022-04-04", "2022-04-05", "2022-04-06", "2022-04-07", "2022-04-08", ], "some_other": [ "2022.03.15.", "2022.12.25.", "2022-01-01", "2022-04-04", "2022-04-05", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "all_not_holiday", "country_code": "hu", }, "out": { "success": True, }, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "some_other", "country_code": "hu", "mostly": 0.9, }, "out": { "success": False, }, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.to_be_not_holiday" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ( "mostly", "country_code", ) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": [ "hackathon-22", "experimental", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@szecsip", # Don't forget to add your github handle here! ], "requirements": ["holidays"], } success_keys = ( "country_code", "mostly", ) if __name__ == "__main__": ExpectColumnValuesToBeNotHoliday().print_diagnostic_checklist()
ExpectColumnValuesToBeNotHoliday
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 10033, "end": 10099 }
class ____(_ReplicatePermission): pass
ReplicatePermissionOutput
python
jina-ai__jina
tests/integration/docarray_v2/csp/SampleClipExecutor/executor.py
{ "start": 277, "end": 493 }
class ____(BaseDoc): text: Optional[str] = None url: Optional[AnyUrl] = None bytes: Optional[ImageBytes] = None num_tokens: Optional[int] = None input_ids: Optional[List[int]] = None
TextAndImageDoc
python
readthedocs__readthedocs.org
readthedocs/projects/utils.py
{ "start": 159, "end": 945 }
class ____: """ A class that implements just the write method of the file-like interface. This class can be used for generating StreamingHttpResponse. See: https://docs.djangoproject.com/en/2.2/howto/outputting-csv/#streaming-large-csv-files """ def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value def get_csv_file(filename, csv_data): """Get a CSV file to be downloaded as an attachment.""" pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse( (writer.writerow(row) for row in csv_data), content_type="text/csv", ) response["Content-Disposition"] = f'attachment; filename="{filename}"' return response
Echo
python
kamyu104__LeetCode-Solutions
Python/adding-spaces-to-a-string.py
{ "start": 48, "end": 508 }
class ____(object): def addSpaces(self, s, spaces): """ :type s: str :type spaces: List[int] :rtype: str """ prev = len(s) s = list(s) s.extend([None]*len(spaces)) for i in reversed(xrange(len(spaces))): for j in reversed(xrange(spaces[i], prev)): s[j+1+i] = s[j] s[spaces[i]+i] = ' ' prev = spaces[i] return "".join(s)
Solution
python
ray-project__ray
python/ray/train/v2/_internal/util.py
{ "start": 2706, "end": 9074 }
class ____(Generic[T]): """Thin wrapper around ray.put to manually control dereferencing.""" def __init__(self, obj: T): self._ref = ray.put(obj) def get(self) -> T: return ray.get(self._ref) def date_str(include_ms: bool = False): pattern = "%Y-%m-%d_%H-%M-%S" if include_ms: pattern += ".%f" return datetime.today().strftime(pattern) def time_monotonic(): return time.monotonic() def _copy_doc(copy_func): def wrapped(func): func.__doc__ = copy_func.__doc__ return func return wrapped def ray_get_safe( object_refs: Union[ObjectRef, List[ObjectRef]], ) -> Union[Any, List[Any]]: """This is a safe version of `ray.get` that raises an exception immediately if an input task dies, while the others are still running. TODO(ml-team, core-team): This is NOT a long-term solution, and we should not maintain this function indefinitely. This is a mitigation for a Ray Core bug, and should be removed when that is fixed. See here: https://github.com/ray-project/ray/issues/47204 Args: object_refs: A single or list of object refs to wait on. Returns: task_outputs: The outputs of the tasks. Raises: `RayTaskError`/`RayActorError`: if any of the tasks encounter a runtime error or fail due to actor/task death (ex: node failure). """ is_list = isinstance(object_refs, list) object_refs = object_refs if is_list else [object_refs] unready = object_refs task_to_output = {} while unready: ready, unready = ray.wait(unready, num_returns=1) if ready: for task, task_output in zip(ready, ray.get(ready)): task_to_output[task] = task_output assert len(task_to_output) == len(object_refs) ordered_outputs = [task_to_output[task] for task in object_refs] return ordered_outputs if is_list else ordered_outputs[0] @contextlib.contextmanager def invoke_context_managers( context_managers: List[ContextManager], ) -> Generator[None, None, None]: """ Utility to invoke a list of context managers and yield sequentially. Args: context_managers: List of context managers to invoke. """ with contextlib.ExitStack() as stack: for context_manager in context_managers: stack.enter_context(context_manager()) yield def get_module_name(obj: object) -> str: """Returns the full module name of the given object, including its qualified name. Args: obj: The object (class, function, etc.) whose module name is required. Returns: Full module and qualified name as a string. """ return f"{obj.__module__}.{obj.__qualname__}" def get_callable_name(fn: Callable) -> str: """Returns a readable name for any callable. Examples: >>> get_callable_name(lambda x: x) '<lambda>' >>> def foo(a, b): pass >>> get_callable_name(foo) 'foo' >>> from functools import partial >>> bar = partial(partial(foo, a=1), b=2) >>> get_callable_name(bar) 'foo' >>> class Dummy: ... def __call__(self, a, b): pass >>> get_callable_name(Dummy()) 'Dummy' """ if isinstance(fn, functools.partial): return get_callable_name(fn.func) # Use __name__ for regular functions and lambdas if hasattr(fn, "__name__"): return fn.__name__ # Fallback to the class name for objects that implement __call__ return fn.__class__.__name__ def construct_user_exception_with_traceback( e: BaseException, exclude_frames: int = 0 ) -> UserExceptionWithTraceback: """Construct a UserExceptionWithTraceback from a base exception. Args: e: The base exception to construct a UserExceptionWithTraceback from. exclude_frames: The number of frames to exclude from the beginnning of the traceback. Returns: A UserExceptionWithTraceback object. """ # TODO(justinvyu): This is brittle and may break if the call stack # changes. Figure out a more robust way to exclude these frames. exc_traceback_str = traceback.format_exc( limit=-(len(traceback.extract_tb(e.__traceback__)) - exclude_frames) ) logger.error(f"Error in training function:\n{exc_traceback_str}") return UserExceptionWithTraceback(e, traceback_str=exc_traceback_str) def _in_ray_train_worker() -> bool: """Check if the current process is a Ray Train V2 worker.""" from ray.train.v2._internal.execution.train_fn_utils import get_train_fn_utils try: get_train_fn_utils() return True except RuntimeError: return False def requires_train_worker(raise_in_tune_session: bool = False) -> Callable: """Check that the caller is a Ray Train worker spawned by Ray Train, with access to training function utilities. Args: raise_in_tune_session: Whether to raise a specific error message if the caller is in a Tune session. If True, will raise a DeprecationWarning. Returns: A decorator that performs this check, which raises an error if the caller is not a Ray Train worker. """ def _wrap(fn: Callable) -> Callable: @functools.wraps(fn) def _wrapped_fn(*args, **kwargs): from ray.tune.trainable.trainable_fn_utils import _in_tune_session if raise_in_tune_session and _in_tune_session(): raise DeprecationWarning( f"`ray.train.{fn.__name__}` is deprecated when running in a function " "passed to Ray Tune. Please use the equivalent `ray.tune` API instead. " "See this issue for more context: " "https://github.com/ray-project/ray/issues/49454" ) if not _in_ray_train_worker(): raise RuntimeError( f"`{fn.__name__}` cannot be used outside of a Ray Train training function. " "You are calling this API from the driver or another non-training process. " "These utilities are only available within a function launched by `trainer.fit()`." ) return fn(*args, **kwargs) return _wrapped_fn return _wrap
ObjectRefWrapper
python
readthedocs__readthedocs.org
readthedocs/core/tests/test_permissions.py
{ "start": 435, "end": 3760 }
class ____(TestCase): def setUp(self): self.owner = get(User) self.project = get(Project) self.organization = get( Organization, owners=[self.owner], projects=[self.project] ) self.team = get(Team, organization=self.organization, access=ADMIN_ACCESS) self.team_read_only = get( Team, organization=self.organization, access=READ_ONLY_ACCESS ) self.user_admin = get(User) self.user_on_same_team = get(User) self.user_read_only = get(User) self.organization.add_member(self.user_admin, self.team) self.organization.add_member(self.user_on_same_team, self.team) self.organization.add_member(self.user_read_only, self.team_read_only) self.another_owner = get(User) self.another_organization = get(Organization, owners=[self.another_owner]) self.another_team = get( Team, organization=self.another_organization, access=ADMIN_ACCESS ) self.another_team_read_only = get( Team, organization=self.another_organization, access=READ_ONLY_ACCESS ) self.another_user_admin = get(User) self.another_user_read_only = get(User) self.another_organization.add_member(self.another_user_admin, self.another_team) self.another_organization.add_member( self.another_user_read_only, self.another_team_read_only ) def test_members(self): users = AdminPermission.members(self.organization) self.assertQuerySetEqual( users, [self.owner, self.user_admin, self.user_read_only, self.user_on_same_team], ordered=False, transform=lambda x: x, ) users = AdminPermission.members(self.another_organization) self.assertQuerySetEqual( users, [self.another_owner, self.another_user_admin, self.another_user_read_only], ordered=False, transform=lambda x: x, ) def test_members_for_user(self): # Owner should be able to see all members. users = AdminPermission.members(self.organization, user=self.owner) self.assertQuerySetEqual( users, [self.owner, self.user_admin, self.user_read_only, self.user_on_same_team], ordered=False, transform=lambda x: x, ) # User is able to see users that are on the same team, and owners. users = AdminPermission.members(self.organization, user=self.user_admin) self.assertQuerySetEqual( users, [self.owner, self.user_admin, self.user_on_same_team], ordered=False, transform=lambda x: x, ) users = AdminPermission.members(self.organization, user=self.user_on_same_team) self.assertQuerySetEqual( users, [self.owner, self.user_admin, self.user_on_same_team], ordered=False, transform=lambda x: x, ) users = AdminPermission.members(self.organization, user=self.user_read_only) self.assertQuerySetEqual( users, [self.owner, self.user_read_only], ordered=False, transform=lambda x: x, )
TestPermissionsWithOrganizations