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 | numba__numba | numba/parfors/array_analysis.py | {
"start": 38443,
"end": 40140
} | class ____(object):
"""
Array analysis should be able to analyze all the function
calls that it adds to the IR. That way, array analysis can
be run as often as needed and you should get the same
equivalencies. One modification to the IR that array analysis
makes is the insertion of wrap_index calls. Thus, repeated
array analysis passes should be able to analyze these wrap_index
calls. The difficulty of these calls is that the equivalence
class of the left-hand side of the assignment is not present in
the arguments to wrap_index in the right-hand side. Instead,
the equivalence class of the wrap_index output is a combination
of the wrap_index args. The important thing to
note is that if the equivalence classes of the slice size
and the dimension's size are the same for two wrap index
calls then we can be assured of the answer being the same.
So, we maintain the wrap_map dict that maps from a tuple
of equivalence class ids for the slice and dimension size
to some new equivalence class id for the output size.
However, when we are analyzing the first such wrap_index
call we don't have a variable there to associate to the
size since we're in the process of analyzing the instruction
that creates that mapping. So, instead we return an object
of this special class and analyze_inst will establish the
connection between a tuple of the parts of this object
below and the left-hand side variable.
"""
def __init__(self, slice_size, dim_size):
self.slice_size = slice_size
self.dim_size = dim_size
| WrapIndexMeta |
python | pydantic__pydantic | pydantic/color.py | {
"start": 1252,
"end": 3324
} | class ____:
"""Internal use only as a representation of a color."""
__slots__ = 'r', 'g', 'b', 'alpha', '_tuple'
def __init__(self, r: float, g: float, b: float, alpha: Optional[float]):
self.r = r
self.g = g
self.b = b
self.alpha = alpha
self._tuple: tuple[float, float, float, Optional[float]] = (r, g, b, alpha)
def __getitem__(self, item: Any) -> Any:
return self._tuple[item]
# these are not compiled here to avoid import slowdown, they'll be compiled the first time they're used, then cached
_r_255 = r'(\d{1,3}(?:\.\d+)?)'
_r_comma = r'\s*,\s*'
_r_alpha = r'(\d(?:\.\d+)?|\.\d+|\d{1,2}%)'
_r_h = r'(-?\d+(?:\.\d+)?|-?\.\d+)(deg|rad|turn)?'
_r_sl = r'(\d{1,3}(?:\.\d+)?)%'
r_hex_short = r'\s*(?:#|0x)?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?\s*'
r_hex_long = r'\s*(?:#|0x)?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?\s*'
# CSS3 RGB examples: rgb(0, 0, 0), rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 50%)
r_rgb = rf'\s*rgba?\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
# CSS3 HSL examples: hsl(270, 60%, 50%), hsla(270, 60%, 50%, 0.5), hsla(270, 60%, 50%, 50%)
r_hsl = rf'\s*hsla?\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
# CSS4 RGB examples: rgb(0 0 0), rgb(0 0 0 / 0.5), rgb(0 0 0 / 50%), rgba(0 0 0 / 50%)
r_rgb_v4_style = rf'\s*rgba?\(\s*{_r_255}\s+{_r_255}\s+{_r_255}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
# CSS4 HSL examples: hsl(270 60% 50%), hsl(270 60% 50% / 0.5), hsl(270 60% 50% / 50%), hsla(270 60% 50% / 50%)
r_hsl_v4_style = rf'\s*hsla?\(\s*{_r_h}\s+{_r_sl}\s+{_r_sl}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
# colors where the two hex characters are the same, if all colors match this the short version of hex colors can be used
repeat_colors = {int(c * 2, 16) for c in '0123456789abcdef'}
rads = 2 * math.pi
@deprecated(
'The `Color` class is deprecated, use `pydantic_extra_types` instead. '
'See https://docs.pydantic.dev/latest/api/pydantic_extra_types_color/.',
category=PydanticDeprecatedSince20,
)
| RGBA |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/horizontal_shard.py | {
"start": 12706,
"end": 16712
} | class ____(ORMOption):
"""a loader option for statements to apply a specific shard id to the
primary query as well as for additional relationship and column
loaders.
The :class:`_horizontal.set_shard_id` option may be applied using
the :meth:`_sql.Executable.options` method of any executable statement::
stmt = (
select(MyObject)
.where(MyObject.name == "some name")
.options(set_shard_id("shard1"))
)
Above, the statement when invoked will limit to the "shard1" shard
identifier for the primary query as well as for all relationship and
column loading strategies, including eager loaders such as
:func:`_orm.selectinload`, deferred column loaders like :func:`_orm.defer`,
and the lazy relationship loader :func:`_orm.lazyload`.
In this way, the :class:`_horizontal.set_shard_id` option has much wider
scope than using the "shard_id" argument within the
:paramref:`_orm.Session.execute.bind_arguments` dictionary.
.. versionadded:: 2.0.0
"""
__slots__ = ("shard_id", "propagate_to_loaders")
def __init__(
self, shard_id: ShardIdentifier, propagate_to_loaders: bool = True
):
"""Construct a :class:`_horizontal.set_shard_id` option.
:param shard_id: shard identifier
:param propagate_to_loaders: if left at its default of ``True``, the
shard option will take place for lazy loaders such as
:func:`_orm.lazyload` and :func:`_orm.defer`; if False, the option
will not be propagated to loaded objects. Note that :func:`_orm.defer`
always limits to the shard_id of the parent row in any case, so the
parameter only has a net effect on the behavior of the
:func:`_orm.lazyload` strategy.
"""
self.shard_id = shard_id
self.propagate_to_loaders = propagate_to_loaders
def execute_and_instances(
orm_context: ORMExecuteState,
) -> Result[Unpack[TupleAny]]:
active_options: Union[
None,
QueryContext.default_load_options,
Type[QueryContext.default_load_options],
_BulkUDCompileState.default_update_options,
Type[_BulkUDCompileState.default_update_options],
]
if orm_context.is_select:
active_options = orm_context.load_options
elif orm_context.is_update or orm_context.is_delete:
active_options = orm_context.update_delete_options
else:
active_options = None
session = orm_context.session
assert isinstance(session, ShardedSession)
def iter_for_shard(
shard_id: ShardIdentifier,
) -> Result[Unpack[TupleAny]]:
bind_arguments = dict(orm_context.bind_arguments)
bind_arguments["shard_id"] = shard_id
orm_context.update_execution_options(identity_token=shard_id)
return orm_context.invoke_statement(bind_arguments=bind_arguments)
for orm_opt in orm_context._non_compile_orm_options:
# TODO: if we had an ORMOption that gets applied at ORM statement
# execution time, that would allow this to be more generalized.
# for now just iterate and look for our options
if isinstance(orm_opt, set_shard_id):
shard_id = orm_opt.shard_id
break
else:
if active_options and active_options._identity_token is not None:
shard_id = active_options._identity_token
elif "_sa_shard_id" in orm_context.execution_options:
shard_id = orm_context.execution_options["_sa_shard_id"]
elif "shard_id" in orm_context.bind_arguments:
shard_id = orm_context.bind_arguments["shard_id"]
else:
shard_id = None
if shard_id is not None:
return iter_for_shard(shard_id)
else:
partial = []
for shard_id in session.execute_chooser(orm_context):
result_ = iter_for_shard(shard_id)
partial.append(result_)
return partial[0].merge(*partial[1:])
| set_shard_id |
python | huggingface__transformers | src/transformers/models/cwm/modeling_cwm.py | {
"start": 2051,
"end": 8390
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: CwmConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = inv_freq
@staticmethod
def compute_default_rope_parameters(
config: Optional[CwmConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
base = config.rope_parameters["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
@use_kernel_func_from_hub("rotary_pos_emb")
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
| CwmRotaryEmbedding |
python | PrefectHQ__prefect | src/prefect/_internal/concurrency/services.py | {
"start": 12656,
"end": 14534
} | class ____(
_QueueServiceBase[tuple[Unpack[Ts], concurrent.futures.Future[R]]]
):
"""Queued service that provides a future that is signalled with the acquired result for each item
If there was a failure acquiring, the future result is set to the exception.
Type Parameters:
Ts: the tuple of types that make up sent arguments
R: the type returned for each item once acquired
"""
async def _handle(
self, item: tuple[Unpack[Ts], concurrent.futures.Future[R]]
) -> None:
send_item, future = item[:-1], item[-1]
try:
response = await self.acquire(*send_item)
except Exception as exc:
# If the request to the increment endpoint fails in a non-standard
# way, we need to set the future's result so it'll be re-raised in
# the context of the caller.
future.set_exception(exc)
raise exc
else:
future.set_result(response)
@abc.abstractmethod
async def acquire(self, *args: Unpack[Ts]) -> R:
raise NotImplementedError
def send(self, item: tuple[Unpack[Ts]]) -> concurrent.futures.Future[R]:
with self._lock:
if self._stopped:
raise RuntimeError("Cannot put items in a stopped service instance.")
logger.debug("Service %r enqueuing item %r", self, item)
future: concurrent.futures.Future[R] = concurrent.futures.Future()
self._queue.put_nowait((*self._prepare_item(item), future))
return future
def _prepare_item(self, item: tuple[Unpack[Ts]]) -> tuple[Unpack[Ts]]:
"""
Prepare an item for submission to the service. This is called before
the item is sent to the service.
The default implementation returns the item unchanged.
"""
return item
| FutureQueueService |
python | streamlit__streamlit | lib/tests/streamlit/elements/empty_test.py | {
"start": 767,
"end": 1030
} | class ____(DeltaGeneratorTestCase):
"""Test Public Streamlit Public APIs."""
def test_st_empty(self):
"""Test st.empty."""
st.empty()
el = self.get_delta_from_queue().new_element
assert el.empty == EmptyProto()
| StEmptyAPITest |
python | pypa__pipenv | pipenv/vendor/tomlkit/exceptions.py | {
"start": 1766,
"end": 2004
} | class ____(ParseError):
"""
A date field was improperly specified.
"""
def __init__(self, line: int, col: int) -> None:
message = "Invalid time"
super().__init__(line, col, message=message)
| InvalidTimeError |
python | pallets__click | src/click/types.py | {
"start": 5592,
"end": 5750
} | class ____(ParamType):
is_composite = True
@property
def arity(self) -> int: # type: ignore
raise NotImplementedError()
| CompositeParamType |
python | walkccc__LeetCode | solutions/2638. Count the Number of K-Free Subsets/2638.py | {
"start": 0,
"end": 465
} | class ____:
def countTheNumOfKFreeSubsets(self, nums: list[int], k: int) -> int:
modToSubset = collections.defaultdict(set)
for num in nums:
modToSubset[num % k].add(num)
prevNum = -k
skip = 0
pick = 0
for subset in modToSubset.values():
for num in sorted(subset):
skip, pick = (skip + pick,
1 + skip + (0 if num - prevNum == k else pick))
prevNum = num
return 1 + skip + pick
| Solution |
python | doocs__leetcode | solution/3200-3299/3227.Vowels Game in a String/Solution.py | {
"start": 0,
"end": 133
} | class ____:
def doesAliceWin(self, s: str) -> bool:
vowels = set("aeiou")
return any(c in vowels for c in s)
| Solution |
python | apache__airflow | shared/logging/src/airflow_shared/logging/structlog.py | {
"start": 6297,
"end": 24364
} | class ____(Generic[LogOutputType]):
def __init__(
self,
cls: Callable[[str | None, LogOutputType | None], WrappedLogger],
io: LogOutputType | None = None,
):
self.cls = cls
self.io = io
def __call__(self, logger_name: str | None = None, *args: Any) -> WrappedLogger:
return self.cls(logger_name, self.io)
def logger_name(logger: Any, method_name: Any, event_dict: EventDict) -> EventDict:
if logger_name := (event_dict.pop("logger_name", None) or getattr(logger, "name", None)):
event_dict.setdefault("logger", logger_name)
return event_dict
# `eyJ` is `{"` in base64 encoding -- and any value that starts like that is very likely a JWT
# token. Better safe than sorry
def redact_jwt(logger: Any, method_name: str, event_dict: EventDict) -> EventDict:
for k, v in event_dict.items():
if isinstance(v, str):
event_dict[k] = re.sub(JWT_PATTERN, "eyJ***", v)
return event_dict
def drop_positional_args(logger: Any, method_name: Any, event_dict: EventDict) -> EventDict:
event_dict.pop("positional_args", None)
return event_dict
# This is a placeholder fn, that is "edited" in place via the `suppress_logs_and_warning` decorator
# The reason we need to do it this way is that structlog caches loggers on first use, and those include the
# configured processors, so we can't get away with changing the config as it won't have any effect once the
# logger obj is created and has been used once
def respect_stdlib_disable(logger: Any, method_name: Any, event_dict: EventDict) -> EventDict:
return event_dict
@cache
def structlog_processors(
json_output: bool,
log_format: str = "",
colors: bool = True,
callsite_parameters: tuple[CallsiteParameter, ...] = (),
):
"""
Create the correct list of structlog processors for the given config.
Return value is a tuple of three elements:
1. A list of processors shared for structlog and stdlib
2. The final processor/renderer (one that outputs a string) for use with structlog.stdlib.ProcessorFormatter
``callsite_parameters`` specifies the keys to add to the log event dict. If ``log_format`` is specified
then anything callsite related will be added to this list
:meta private:
"""
timestamper = structlog.processors.MaybeTimeStamper(fmt="iso")
# Processors shared between stdlib handlers and structlog processors
shared_processors: list[structlog.typing.Processor] = [
respect_stdlib_disable,
timestamper,
structlog.contextvars.merge_contextvars,
structlog.processors.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
logger_name,
redact_jwt,
structlog.processors.StackInfoRenderer(),
]
if log_format:
# Maintain the order if any params that are given explicitly, then add on anything needed for the
# format string (so use a dict with None as the values as set doesn't preserve order)
params = {
param: None
for param in itertools.chain(
callsite_parameters or [], PercentFormatRender.callsite_params_from_fmt_string(log_format)
)
}
shared_processors.append(
structlog.processors.CallsiteParameterAdder(list(params.keys()), additional_ignores=[__name__])
)
elif callsite_parameters:
shared_processors.append(
structlog.processors.CallsiteParameterAdder(callsite_parameters, additional_ignores=[__name__])
)
# Imports to suppress showing code from these modules. We need the import to get the filepath for
# structlog to ignore.
import contextlib
import click
suppress = (click, contextlib)
try:
import httpcore
suppress += (httpcore,)
except ImportError:
pass
try:
import httpx
suppress += (httpx,)
except ImportError:
pass
if json_output:
dict_exc_formatter = structlog.tracebacks.ExceptionDictTransformer(
use_rich=False, show_locals=False, suppress=suppress
)
dict_tracebacks = structlog.processors.ExceptionRenderer(dict_exc_formatter)
import msgspec
def json_dumps(msg, default):
# Note: this is likely an "expensive" step, but lets massage the dict order for nice
# viewing of the raw JSON logs.
# Maybe we don't need this once the UI renders the JSON instead of displaying the raw text
msg = {
"timestamp": msg.pop("timestamp"),
"level": msg.pop("level"),
"event": msg.pop("event"),
**msg,
}
return msgspec.json.encode(msg, enc_hook=default)
json = structlog.processors.JSONRenderer(serializer=json_dumps)
def json_processor(logger: Any, method_name: Any, event_dict: EventDict) -> str:
return json(logger, method_name, event_dict).decode("utf-8")
shared_processors.extend(
(
dict_tracebacks,
structlog.processors.UnicodeDecoder(),
),
)
return shared_processors, json_processor, json
if os.getenv("DEV", "") != "":
# Only use Rich in dev -- otherwise for "production" deployments it makes the logs harder to read as
# it uses lots of ANSI escapes and non ASCII characters. Simpler is better for non-dev non-JSON
exc_formatter = structlog.dev.RichTracebackFormatter(
# These values are picked somewhat arbitrarily to produce useful-but-compact tracebacks. If
# we ever need to change these then they should be configurable.
extra_lines=0,
max_frames=30,
indent_guides=False,
suppress=suppress,
)
else:
exc_formatter = structlog.dev.plain_traceback
my_styles = structlog.dev.ConsoleRenderer.get_default_level_styles(colors=colors)
if colors:
my_styles["debug"] = structlog.dev.CYAN
if log_format:
console = PercentFormatRender(
fmt=log_format,
exception_formatter=exc_formatter,
level_styles=my_styles,
colors=colors,
)
else:
if callsite_parameters == (CallsiteParameter.FILENAME, CallsiteParameter.LINENO):
# Nicer formatting of the default callsite config
def log_loc(logger: Any, method_name: Any, event_dict: EventDict) -> EventDict:
if (
event_dict.get("logger") != "py.warnings"
and "filename" in event_dict
and "lineno" in event_dict
):
event_dict["loc"] = f"{event_dict.pop('filename')}:{event_dict.pop('lineno')}"
return event_dict
shared_processors.append(log_loc)
console = structlog.dev.ConsoleRenderer(
exception_formatter=exc_formatter,
level_styles=my_styles,
colors=colors,
)
return shared_processors, console, console
def configure_logging(
*,
json_output: bool = False,
log_level: str = "DEBUG",
log_format: str = "",
stdlib_config: dict | None = None,
extra_processors: Sequence[Processor] | None = None,
callsite_parameters: Iterable[CallsiteParameter] | None = None,
colors: bool = True,
output: LogOutputType | None = None,
namespace_log_levels: str | dict[str, str] | None = None,
cache_logger_on_first_use: bool = True,
):
"""
Configure structlog (and stbilb's logging to send via structlog processors too).
If percent_log_format is passed then it will be handled in a similar mode to stdlib, including
interpolations such as ``%(asctime)s`` etc.
:param json_output: Set to true to write all logs as JSON (one per line)
:param log_level: The default log level to use for most logs
:param log_format: A percent-style log format to write non JSON logs with.
:param output: Where to write the logs to. If ``json_output`` is true this must be a binary stream
:param colors: Whether to use colors for non-JSON logs. This only works if standard out is a TTY (that is,
an interactive session), unless overridden by environment variables described below.
Please note that disabling colors also disables all styling, including bold and italics.
The following environment variables control color behavior (set to any non-empty value to activate):
* ``NO_COLOR`` - Disables colors completely. This takes precedence over all other settings,
including ``FORCE_COLOR``.
* ``FORCE_COLOR`` - Forces colors to be enabled, even when output is not going to a TTY. This only
takes effect if ``NO_COLOR`` is not set.
:param callsite_parameters: A list parameters about the callsite (line number, function name etc) to
include in the logs.
If ``log_format`` is specified, then anything required to populate that (such as ``%(lineno)d``) will
be automatically included.
:param namespace_log_levels: Levels of extra loggers to configure.
To make this easier to use, this can be a string consisting of pairs of ``<logger>=<level>`` (either
string, or space delimited) which will set the level for that specific logger.
For example::
``sqlalchemy=INFO sqlalchemy.engine=DEBUG``
"""
if "fatal" not in NAME_TO_LEVEL:
NAME_TO_LEVEL["fatal"] = NAME_TO_LEVEL["critical"]
def is_atty():
return sys.stdout is not None and hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
colors = os.environ.get("NO_COLOR", "") == "" and (
os.environ.get("FORCE_COLOR", "") != "" or (colors and is_atty())
)
stdlib_config = stdlib_config or {}
extra_processors = extra_processors or ()
PER_LOGGER_LEVELS[""] = NAME_TO_LEVEL[log_level.lower()]
# Extract per-logger-tree levels and set them
if isinstance(namespace_log_levels, str):
log_from_level = partial(re.compile(r"\s*=\s*").split, maxsplit=2)
namespace_log_levels = {
log: level for log, level in map(log_from_level, re.split(r"[\s,]+", namespace_log_levels))
}
if namespace_log_levels:
for log, level in namespace_log_levels.items():
try:
loglevel = NAME_TO_LEVEL[level.lower()]
except KeyError:
raise ValueError(f"Invalid log level for logger {log!r}: {level!r}") from None
else:
PER_LOGGER_LEVELS[log] = loglevel
shared_pre_chain, for_stdlib, for_structlog = structlog_processors(
json_output,
log_format=log_format,
colors=colors,
callsite_parameters=tuple(callsite_parameters or ()),
)
shared_pre_chain += list(extra_processors)
pre_chain: list[structlog.typing.Processor] = [structlog.stdlib.add_logger_name] + shared_pre_chain
# Don't cache the loggers during tests, it makes it hard to capture them
if "PYTEST_VERSION" in os.environ:
cache_logger_on_first_use = False
std_lib_formatter: list[Processor] = [
# TODO: Don't include this if we are using PercentFormatter -- it'll delete something we
# just have to recreated!
structlog.stdlib.ProcessorFormatter.remove_processors_meta,
drop_positional_args,
for_stdlib,
]
wrapper_class = cast("type[BindableLogger]", make_filtering_logger())
if json_output:
logger_factory = LoggerFactory(NamedBytesLogger, io=output)
else:
# There is no universal way of telling if a file-like-object is binary (and needs bytes) or text that
# works for files, sockets and io.StringIO/BytesIO.
# If given a binary object, wrap it in a text mode wrapper
if output is not None and not hasattr(output, "encoding"):
output = io.TextIOWrapper(output, line_buffering=True)
logger_factory = LoggerFactory(NamedWriteLogger, io=output)
structlog.configure(
processors=shared_pre_chain + [for_structlog],
cache_logger_on_first_use=cache_logger_on_first_use,
wrapper_class=wrapper_class,
logger_factory=logger_factory,
)
import logging.config
config = {**stdlib_config}
config.setdefault("version", 1)
config.setdefault("disable_existing_loggers", False)
config["formatters"] = {**config.get("formatters", {})}
config["handlers"] = {**config.get("handlers", {})}
config["loggers"] = {**config.get("loggers", {})}
config["formatters"].update(
{
"structlog": {
"()": structlog.stdlib.ProcessorFormatter,
"use_get_message": False,
"processors": std_lib_formatter,
"foreign_pre_chain": pre_chain,
"pass_foreign_args": True,
},
}
)
for section in (config["loggers"], config["handlers"]):
for log_config in section.values():
# We want everything to go via structlog, remove whatever the user might have configured
log_config.pop("stream", None)
log_config.pop("formatter", None)
# log_config.pop("handlers", None)
if output and not hasattr(output, "encoding"):
# This is a BinaryIO, we need to give logging.StreamHandler a TextIO
output = codecs.lookup("utf-8").streamwriter(output) # type: ignore
config["handlers"].update(
{
"default": {
"level": log_level.upper(),
"class": "logging.StreamHandler",
"formatter": "structlog",
"stream": output,
},
}
)
config["loggers"].update(
{
# Set Airflow logging to the level requested, but most everything else at "INFO"
"airflow": {"level": log_level.upper()},
# These ones are too chatty even at info
"httpx": {"level": "WARN"},
"sqlalchemy.engine": {"level": "WARN"},
}
)
config["root"] = {
"handlers": ["default"],
"level": "INFO",
"propagate": True,
}
logging.config.dictConfig(config)
def init_log_folder(directory: str | os.PathLike[str], new_folder_permissions: int):
"""
Prepare the log folder and ensure its mode is as configured.
To handle log writing when tasks are impersonated, the log files need to
be writable by the user that runs the Airflow command and the user
that is impersonated. This is mainly to handle corner cases with the
SubDagOperator. When the SubDagOperator is run, all of the operators
run under the impersonated user and create appropriate log files
as the impersonated user. However, if the user manually runs tasks
of the SubDagOperator through the UI, then the log files are created
by the user that runs the Airflow command. For example, the Airflow
run command may be run by the `airflow_sudoable` user, but the Airflow
tasks may be run by the `airflow` user. If the log files are not
writable by both users, then it's possible that re-running a task
via the UI (or vice versa) results in a permission error as the task
tries to write to a log file created by the other user.
We leave it up to the user to manage their permissions by exposing configuration for both
new folders and new log files. Default is to make new log folders and files group-writeable
to handle most common impersonation use cases. The requirement in this case will be to make
sure that the same group is set as default group for both - impersonated user and main airflow
user.
"""
directory = Path(directory)
for parent in reversed(Path(directory).parents):
parent.mkdir(mode=new_folder_permissions, exist_ok=True)
directory.mkdir(mode=new_folder_permissions, exist_ok=True)
def init_log_file(
base_log_folder: str | os.PathLike[str],
local_relative_path: str | os.PathLike[str],
*,
new_folder_permissions: int = 0o775,
new_file_permissions: int = 0o664,
) -> Path:
"""
Ensure log file and parent directories are created with the correct permissions.
Any directories that are missing are created with the right permission bits.
See above ``init_log_folder`` method for more detailed explanation.
"""
full_path = Path(base_log_folder, local_relative_path)
init_log_folder(full_path.parent, new_folder_permissions)
try:
full_path.touch(new_file_permissions)
except OSError as e:
log = structlog.get_logger(__name__)
log.warning("OSError while changing ownership of the log file. %s", e)
return full_path
def reconfigure_logger(
logger: WrappedLogger, without_processor_type: type, level_override: int | None = None
):
procs = getattr(logger, "_processors", None)
if procs is None:
procs = structlog.get_config()["processors"]
procs = [proc for proc in procs if not isinstance(proc, without_processor_type)]
return structlog.wrap_logger(
getattr(logger, "_logger", None),
processors=procs,
**getattr(logger, "_context", {}),
__level_override=level_override,
)
if __name__ == "__main__":
configure_logging(
# json_output=True,
log_format="[%(blue)s%(asctime)s%(reset)s] {%(blue)s%(filename)s:%(reset)s%(lineno)d} %(log_color)s%(levelname)s%(reset)s - %(log_color)s%(message)s%(reset)s",
)
log = logging.getLogger("testing.stlib")
log2 = structlog.get_logger(logger_name="testing.structlog")
def raises():
try:
1 / 0
except ZeroDivisionError:
log.exception("str")
try:
1 / 0
except ZeroDivisionError:
log2.exception("std")
def main():
log.info("in main")
log2.info("in main", key="value")
raises()
main()
| LoggerFactory |
python | django-haystack__django-haystack | test_haystack/test_loading.py | {
"start": 7761,
"end": 8109
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True)
author = indexes.CharField(faceted=True)
title = indexes.CharField()
title_facet = indexes.FacetCharField(facet_for="title")
bare_facet = indexes.FacetCharField()
def get_model(self):
return MockModel
| ExplicitFacetSearchIndex |
python | walkccc__LeetCode | solutions/3314. Construct the Minimum Bitwise Array I/3314.py | {
"start": 0,
"end": 544
} | class ____:
def minBitwiseArray(self, nums: list[int]) -> list[int]:
return [-1 if num == 2 else num - self._getLeadingOneOfLastGroupOfOnes(num)
for num in nums]
def _getLeadingOneOfLastGroupOfOnes(self, num: int) -> int:
"""
Returns the leading one of the last group of 1s in the binary
representation of num. For example, if num = 0b10111, the leading one of
the last group of 1s is 0b100.
"""
leadingOne = 1
while (num & leadingOne) > 0:
leadingOne <<= 1
return leadingOne >> 1
| Solution |
python | getsentry__sentry | src/sentry/replays/lib/event_linking.py | {
"start": 811,
"end": 884
} | class ____(EventLinkPayload):
warning_id: str
| EventLinkPayloadWarningId |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/historical.py | {
"start": 310,
"end": 1836
} | class ____(RepresentedJob):
"""HistoricalPipeline represents a pipeline that executed in the past
and has been reloaded into process by querying the instance. Notably
the user must pass in the pipeline snapshot id that was originally
assigned to the snapshot, rather than recomputing it which could
end up different if the schema of the snapshot has changed
since persistence.
"""
def __init__(
self,
job_snapshot: JobSnap,
identifying_job_snapshot_id: str,
parent_job_snapshot: Optional[JobSnap],
):
self._snapshot = check.inst_param(job_snapshot, "job_snapshot", JobSnap)
self._parent_snapshot = check.opt_inst_param(
parent_job_snapshot, "parent_job_snapshot", JobSnap
)
self._identifying_job_snapshot_id = check.str_param(
identifying_job_snapshot_id, "identifying_job_snapshot_id"
)
self._index = None
@property
def _job_index(self):
if self._index is None:
self._index = JobIndex(
self._snapshot,
self._parent_snapshot,
)
return self._index
@property
def identifying_job_snapshot_id(self):
return self._identifying_job_snapshot_id
@property
def computed_job_snapshot_id(self):
return self._job_index.job_snapshot_id
def get_external_job_source(self) -> Optional[str]:
return self._job_index.job_snapshot.tags.get(EXTERNAL_JOB_SOURCE_TAG_KEY)
| HistoricalJob |
python | kamyu104__LeetCode-Solutions | Python/sqrtx.py | {
"start": 32,
"end": 430
} | class ____(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x < 2:
return x
left, right = 1, x // 2
while left <= right:
mid = left + (right - left) // 2
if mid > x / mid:
right = mid - 1
else:
left = mid + 1
return left - 1
| Solution |
python | pypa__pipenv | pipenv/patched/pip/_internal/operations/install/wheel.py | {
"start": 14457,
"end": 15035
} | class ____(InstallationError):
def __init__(self, entry_point: str) -> None:
super().__init__(
f"Invalid script entry point: {entry_point} - A callable "
"suffix is required. Cf https://packaging.python.org/"
"specifications/entry-points/#use-for-scripts for more "
"information."
)
def _raise_for_invalid_entrypoint(specification: str) -> None:
entry = get_export_entry(specification)
if entry is not None and entry.suffix is None:
raise MissingCallableSuffix(str(entry))
| MissingCallableSuffix |
python | numpy__numpy | numpy/f2py/tests/test_crackfortran.py | {
"start": 5676,
"end": 9645
} | class ____(util.F2PyTest):
"""This test suite tests various expressions that are used as dimension
specifications.
There exists two usage cases where analyzing dimensions
specifications are important.
In the first case, the size of output arrays must be defined based
on the inputs to a Fortran function. Because Fortran supports
arbitrary bases for indexing, for instance, `arr(lower:upper)`,
f2py has to evaluate an expression `upper - lower + 1` where
`lower` and `upper` are arbitrary expressions of input parameters.
The evaluation is performed in C, so f2py has to translate Fortran
expressions to valid C expressions (an alternative approach is
that a developer specifies the corresponding C expressions in a
.pyf file).
In the second case, when user provides an input array with a given
size but some hidden parameters used in dimensions specifications
need to be determined based on the input array size. This is a
harder problem because f2py has to solve the inverse problem: find
a parameter `p` such that `upper(p) - lower(p) + 1` equals to the
size of input array. In the case when this equation cannot be
solved (e.g. because the input array size is wrong), raise an
error before calling the Fortran function (that otherwise would
likely crash Python process when the size of input arrays is
wrong). f2py currently supports this case only when the equation
is linear with respect to unknown parameter.
"""
suffix = ".f90"
code_template = textwrap.dedent("""
function get_arr_size_{count}(a, n) result (length)
integer, intent(in) :: n
integer, dimension({dimspec}), intent(out) :: a
integer length
length = size(a)
end function
subroutine get_inv_arr_size_{count}(a, n)
integer :: n
! the value of n is computed in f2py wrapper
!f2py intent(out) n
integer, dimension({dimspec}), intent(in) :: a
if (a({first}).gt.0) then
! print*, "a=", a
endif
end subroutine
""")
linear_dimspecs = [
"n", "2*n", "2:n", "n/2", "5 - n/2", "3*n:20", "n*(n+1):n*(n+5)",
"2*n, n"
]
nonlinear_dimspecs = ["2*n:3*n*n+2*n"]
all_dimspecs = linear_dimspecs + nonlinear_dimspecs
code = ""
for count, dimspec in enumerate(all_dimspecs):
lst = [(d.split(":")[0] if ":" in d else "1") for d in dimspec.split(',')]
code += code_template.format(
count=count,
dimspec=dimspec,
first=", ".join(lst),
)
@pytest.mark.parametrize("dimspec", all_dimspecs)
@pytest.mark.slow
def test_array_size(self, dimspec):
count = self.all_dimspecs.index(dimspec)
get_arr_size = getattr(self.module, f"get_arr_size_{count}")
for n in [1, 2, 3, 4, 5]:
sz, a = get_arr_size(n)
assert a.size == sz
@pytest.mark.parametrize("dimspec", all_dimspecs)
def test_inv_array_size(self, dimspec):
count = self.all_dimspecs.index(dimspec)
get_arr_size = getattr(self.module, f"get_arr_size_{count}")
get_inv_arr_size = getattr(self.module, f"get_inv_arr_size_{count}")
for n in [1, 2, 3, 4, 5]:
sz, a = get_arr_size(n)
if dimspec in self.nonlinear_dimspecs:
# one must specify n as input, the call we'll ensure
# that a and n are compatible:
n1 = get_inv_arr_size(a, n)
else:
# in case of linear dependence, n can be determined
# from the shape of a:
n1 = get_inv_arr_size(a)
# n1 may be different from n (for instance, when `a` size
# is a function of some `n` fraction) but it must produce
# the same sized array
sz1, _ = get_arr_size(n1)
assert sz == sz1, (n, n1, sz, sz1)
| TestDimSpec |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard_python3/bundled-services/blobstore/wsgi/main.py | {
"start": 2028,
"end": 2742
} | class ____(blobstore.BlobstoreDownloadHandler):
def get_photo(self, environ, photo_key):
if not blobstore.get(photo_key):
return "Photo key not found", http.HTTPStatus.NOT_FOUND, []
else:
return (
"",
http.HTTPStatus.OK,
list(self.send_blob(environ, photo_key).items()),
)
def get(self, environ):
photo_key = (environ["app.url_args"])[0]
return self.get_photo(environ, photo_key)
# map urls to functions
urls = [
(r"^$", UploadFormHandler),
(r"upload_photo/?$", UploadPhotoHandler),
(r"view_photo/(.+)$", ViewPhotoHandler),
]
# [END gae_blobstore_handler_wsgi]
| ViewPhotoHandler |
python | huggingface__transformers | src/transformers/models/falcon_mamba/modeling_falcon_mamba.py | {
"start": 26120,
"end": 29603
} | class ____(PreTrainedModel):
config: FalconMambaConfig
base_model_prefix = "backbone"
_no_split_modules = ["FalconMambaBlock", "FalconMambaMixer"]
supports_gradient_checkpointing = True
_is_stateful = True
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights."""
std = self.config.initializer_range
if isinstance(module, FalconMambaMixer):
# S4D real initialization. These are not discretized!
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
A = torch.arange(1, module.ssm_state_size + 1, dtype=torch.float32)[None, :]
A = A.expand(module.intermediate_size, -1).contiguous()
init.copy_(module.A_log, torch.log(A))
init.ones_(module.D)
dt_init_std = self.config.time_step_rank**-0.5 * self.config.time_step_scale
if self.config.time_step_init_scheme == "constant":
init.constant_(module.dt_proj.weight, dt_init_std)
elif self.config.time_step_init_scheme == "random":
init.uniform_(module.dt_proj.weight, -dt_init_std, dt_init_std)
dt = torch.exp(
torch.rand(self.config.intermediate_size)
* (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
+ math.log(self.config.time_step_min)
).clamp(min=self.config.time_step_floor)
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
inv_dt = dt + torch.log(-torch.expm1(-dt))
init.copy_(module.dt_proj.bias, inv_dt)
init.kaiming_uniform_(module.conv1d.weight, a=math.sqrt(5))
if module.conv1d.bias is not None:
init.zeros_(module.conv1d.bias)
init.kaiming_uniform_(module.out_proj.weight, a=math.sqrt(5))
if self.config.rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
p = module.out_proj.weight
p /= math.sqrt(self.config.num_hidden_layers)
if isinstance(module, nn.Linear):
init.normal_(module.weight, std=std)
if module.bias is not None:
init.zeros_(module.bias)
elif isinstance(module, FalconMambaRMSNorm):
init.ones_(module.weight)
elif isinstance(module, nn.Embedding):
init.normal_(module.weight, std=std)
@dataclass
@auto_docstring(
custom_intro="""
Class for the FALCON_MAMBA model outputs.
"""
)
| FalconMambaPreTrainedModel |
python | numba__numba | numba/tests/test_remove_dead.py | {
"start": 1943,
"end": 10065
} | class ____(TestCase):
_numba_parallel_test_ = False
def compile_parallel(self, func, arg_types):
return njit(arg_types, parallel=True, fastmath=True)(func)
def test1(self):
typingctx = cpu_target.typing_context
targetctx = cpu_target.target_context
test_ir = compiler.run_frontend(test_will_propagate)
typingctx.refresh()
targetctx.refresh()
args = (types.int64, types.int64, types.int64)
typemap, _, calltypes, _ = type_inference_stage(typingctx, targetctx, test_ir, args, None)
remove_dels(test_ir.blocks)
in_cps, out_cps = copy_propagate(test_ir.blocks, typemap)
apply_copy_propagate(test_ir.blocks, in_cps, get_name_var_table(test_ir.blocks), typemap, calltypes)
remove_dead(test_ir.blocks, test_ir.arg_names, test_ir)
self.assertFalse(findLhsAssign(test_ir, "x"))
def test2(self):
def call_np_random_seed():
np.random.seed(2)
def seed_call_exists(func_ir):
for inst in func_ir.blocks[0].body:
if (isinstance(inst, ir.Assign) and
isinstance(inst.value, ir.Expr) and
inst.value.op == 'call' and
func_ir.get_definition(inst.value.func).attr == 'seed'):
return True
return False
test_ir = compiler.run_frontend(call_np_random_seed)
remove_dead(test_ir.blocks, test_ir.arg_names, test_ir)
self.assertTrue(seed_call_exists(test_ir))
def run_array_index_test(self, func):
A1 = np.arange(6).reshape(2,3)
A2 = A1.copy()
i = 0
pfunc = self.compile_parallel(func, (numba.typeof(A1), numba.typeof(i)))
func(A1, i)
pfunc(A2, i)
np.testing.assert_array_equal(A1, A2)
def test_alias_ravel(self):
def func(A, i):
B = A.ravel()
B[i] = 3
self.run_array_index_test(func)
def test_alias_flat(self):
def func(A, i):
B = A.flat
B[i] = 3
self.run_array_index_test(func)
def test_alias_transpose1(self):
def func(A, i):
B = A.T
B[i,0] = 3
self.run_array_index_test(func)
def test_alias_transpose2(self):
def func(A, i):
B = A.transpose()
B[i,0] = 3
self.run_array_index_test(func)
def test_alias_transpose3(self):
def func(A, i):
B = np.transpose(A)
B[i,0] = 3
self.run_array_index_test(func)
@skip_parfors_unsupported
@needs_blas
def test_alias_ctypes(self):
# use xxnrm2 to test call a C function with ctypes
from numba.np.linalg import _BLAS
xxnrm2 = _BLAS().numba_xxnrm2(types.float64)
def remove_dead_xxnrm2(rhs, lives, call_list):
if call_list == [xxnrm2]:
return rhs.args[4].name not in lives
return False
# adding this handler has no-op effect since this function won't match
# anything else but it's a bit cleaner to save the state and recover
old_remove_handlers = remove_call_handlers[:]
remove_call_handlers.append(remove_dead_xxnrm2)
def func(ret):
a = np.ones(4)
xxnrm2(100, 4, a.ctypes, 1, ret.ctypes)
A1 = np.zeros(1)
A2 = A1.copy()
try:
pfunc = self.compile_parallel(func, (numba.typeof(A1),))
numba.njit(func)(A1)
pfunc(A2)
finally:
# recover global state
remove_call_handlers[:] = old_remove_handlers
self.assertEqual(A1[0], A2[0])
def test_alias_reshape1(self):
def func(A, i):
B = np.reshape(A, (3,2))
B[i,0] = 3
self.run_array_index_test(func)
def test_alias_reshape2(self):
def func(A, i):
B = A.reshape(3,2)
B[i,0] = 3
self.run_array_index_test(func)
def test_alias_func_ext(self):
def func(A, i):
B = dummy_aliased_func(A)
B[i, 0] = 3
# save global state
old_ext_handlers = alias_func_extensions.copy()
try:
alias_func_extensions[('dummy_aliased_func',
'numba.tests.test_remove_dead')] = alias_ext_dummy_func
self.run_array_index_test(func)
finally:
# recover global state
ir_utils.alias_func_extensions = old_ext_handlers
def test_rm_dead_rhs_vars(self):
"""make sure lhs variable of assignment is considered live if used in
rhs (test for #6715).
"""
def func():
for i in range(3):
a = (lambda j: j)(i)
a = np.array(a)
return a
self.assertEqual(func(), numba.njit(func)())
@skip_parfors_unsupported
def test_alias_parfor_extension(self):
"""Make sure aliases are considered in remove dead extension for
parfors.
"""
def func():
n = 11
numba.parfors.parfor.init_prange()
A = np.empty(n)
B = A # create alias to A
for i in numba.prange(n):
A[i] = i
return B
@register_pass(analysis_only=False, mutates_CFG=True)
class LimitedParfor(FunctionPass):
_name = "limited_parfor"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
parfor_pass = numba.parfors.parfor.ParforPass(
state.func_ir,
state.typemap,
state.calltypes,
state.return_type,
state.typingctx,
state.flags.auto_parallel,
state.flags,
state.metadata,
state.parfor_diagnostics
)
remove_dels(state.func_ir.blocks)
parfor_pass.array_analysis.run(state.func_ir.blocks)
parfor_pass._convert_loop(state.func_ir.blocks)
remove_dead(state.func_ir.blocks,
state.func_ir.arg_names,
state.func_ir,
state.typemap)
numba.parfors.parfor.get_parfor_params(state.func_ir.blocks,
parfor_pass.options.fusion,
parfor_pass.nested_fusion_info)
return True
class TestPipeline(compiler.Compiler):
"""Test pipeline that just converts prange() to parfor and calls
remove_dead(). Copy propagation can replace B in the example code
which this pipeline avoids.
"""
def define_pipelines(self):
name = 'test parfor aliasing'
pm = PassManager(name)
pm.add_pass(TranslateByteCode, "analyzing bytecode")
pm.add_pass(FixupArgs, "fix up args")
pm.add_pass(IRProcessing, "processing IR")
pm.add_pass(WithLifting, "Handle with contexts")
# pre typing
if not self.state.flags.no_rewrites:
pm.add_pass(GenericRewrites, "nopython rewrites")
pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants")
pm.add_pass(DeadBranchPrune, "dead branch pruning")
pm.add_pass(InlineClosureLikes,
"inline calls to locally defined closures")
# typing
pm.add_pass(NopythonTypeInference, "nopython frontend")
# lower
pm.add_pass(NativeLowering, "native lowering")
pm.add_pass(NoPythonBackend, "nopython mode backend")
pm.finalize()
return [pm]
test_res = numba.jit(pipeline_class=TestPipeline)(func)()
py_res = func()
np.testing.assert_array_equal(test_res, py_res)
| TestRemoveDead |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 75755,
"end": 80920
} | class ____:
def test_lowpass(self, xp):
wp = 0.2
ws = 0.3
rp = 3
rs = 60
N, Wn = buttord(xp.asarray(wp), ws, rp, rs, False)
b, a = butter(N, _xp_copy_to_numpy(Wn), 'lowpass', False)
w, h = freqz(b, a)
w /= np.pi
assert np.all(-rp < dB(h[w <= wp]))
assert np.all(dB(h[ws <= w]) < -rs)
assert N == 16
xp_assert_close(Wn,
xp.asarray(2.0002776782743284e-01), rtol=1e-15, check_0d=False)
def test_highpass(self, xp):
wp = 0.3
ws = 0.2
rp = 3
rs = 70
N, Wn = buttord(xp.asarray(wp), ws, rp, rs, False)
b, a = butter(N, _xp_copy_to_numpy(Wn), 'highpass', False)
w, h = freqz(b, a)
w /= np.pi
assert np.all(-rp < dB(h[wp <= w]))
assert np.all(dB(h[w <= ws]) < -rs)
assert N == 18
xp_assert_close(Wn,
xp.asarray(2.9996603079132672e-01), rtol=1e-15, check_0d=False)
def test_bandpass(self, xp):
wp = [0.2, 0.5]
ws = [0.1, 0.6]
rp = 3
rs = 80
N, Wn = buttord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
b, a = butter(N, _xp_copy_to_numpy(Wn), 'bandpass', False)
w, h = freqz(b, a)
w /= np.pi
assert np.all((-rp - 0.1) < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])]))
assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < (-rs + 0.1))
assert N == 18
xp_assert_close(
Wn, xp.asarray([1.9998742411409134e-01, 5.0002139595676276e-01]),
rtol=1e-15,
)
@skip_xp_backends(
cpu_only=True, exceptions=["cupy"], reason="optimize.fminbound"
)
def test_bandstop(self, xp):
wp = [0.1, 0.6]
ws = [0.2, 0.5]
rp = 3
rs = 90
N, Wn = buttord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
b, a = butter(N, _xp_copy_to_numpy(Wn), 'bandstop', False)
w, h = freqz(b, a)
w /= np.pi
assert np.all(-rp < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)]))
assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs)
assert N == 20
xp_assert_close(
Wn, xp.asarray([1.4759432329294042e-01, 5.9997365985276407e-01]),
rtol=1e-6
)
def test_analog(self, xp):
wp = 200.
ws = 600.
rp = 3
rs = 60
N, Wn = buttord(xp.asarray(wp), ws, rp, rs, True)
b, a = butter(N, _xp_copy_to_numpy(Wn), 'lowpass', True)
w, h = freqs(b, a)
assert np.all(-rp < dB(h[w <= wp]))
assert np.all(dB(h[ws <= w]) < -rs)
assert N == 7
xp_assert_close(
Wn, xp.asarray(2.0006785355671877e+02), rtol=1e-15, check_0d=False
)
n, Wn = buttord(1., xp.asarray(550/450), 1, 26, analog=True)
assert n == 19
xp_assert_close(
Wn, xp.asarray(1.0361980524629517), rtol=1e-15, check_0d=False
)
assert buttord(1, xp.asarray(1.2), 1, 80, analog=True)[0] == 55
def test_fs_param(self, xp):
wp = [4410, 11025]
ws = [2205, 13230]
rp = 3
rs = 80
fs = 44100
N, Wn = buttord(xp.asarray(wp), xp.asarray(ws), rp, rs, False, fs=fs)
b, a = butter(N, _xp_copy_to_numpy(Wn), 'bandpass', False, fs=fs)
w, h = freqz(b, a, fs=fs)
assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])]))
assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1)
assert N == 18
xp_assert_close(Wn, xp.asarray([4409.722701715714, 11025.47178084662]),
rtol=1e-15)
def test_invalid_input(self):
with pytest.raises(ValueError) as exc_info:
buttord([20, 50], [14, 60], 3, 2)
assert "gpass should be smaller than gstop" in str(exc_info.value)
with pytest.raises(ValueError) as exc_info:
buttord([20, 50], [14, 60], -1, 2)
assert "gpass should be larger than 0.0" in str(exc_info.value)
with pytest.raises(ValueError) as exc_info:
buttord([20, 50], [14, 60], 1, -2)
assert "gstop should be larger than 0.0" in str(exc_info.value)
def test_runtime_warnings(self):
msg = "Order is zero.*|divide by zero encountered"
with pytest.warns(RuntimeWarning, match=msg):
buttord(0.0, 1.0, 3, 60)
def test_ellip_butter(self):
# The purpose of the test is to compare to some known output from past
# scipy versions. The values to compare to are generated with scipy
# 1.9.1 (there is nothing special about this particular version though)
n, wn = buttord([0.1, 0.6], [0.2, 0.5], 3, 60)
assert n == 14
def test_fs_validation(self):
wp = 0.2
ws = 0.3
rp = 3
rs = 60
with pytest.raises(ValueError, match="Sampling.*single scalar"):
buttord(wp, ws, rp, rs, False, fs=np.array([10, 20]))
@make_xp_test_case(cheb1ord)
@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
| TestButtord |
python | walkccc__LeetCode | solutions/3501. Maximize Active Section with Trade II/3501.py | {
"start": 89,
"end": 696
} | class ____:
def __init__(self, nums: list[int]):
self.n = len(nums)
# st[i][j] := max(nums[j..j + 2^i - 1])
self.st = [[0] * (self.n + 1) for _ in range(self.n.bit_length() + 1)]
self.st[0] = nums.copy()
for i in range(1, self.n.bit_length() + 1):
for j in range(self.n - (1 << i) + 1):
self.st[i][j] = max(
self.st[i - 1][j],
self.st[i - 1][j + (1 << (i - 1))])
def query(self, l: int, r: int) -> int:
"""Returns max(nums[l..r])."""
i = (r - l + 1).bit_length() - 1
return max(self.st[i][l], self.st[i][r - (1 << i) + 1])
| SparseTable |
python | tornadoweb__tornado | tornado/template.py | {
"start": 24976,
"end": 25557
} | class ____(_Node):
def __init__(self, value: str, line: int, whitespace: str) -> None:
self.value = value
self.line = line
self.whitespace = whitespace
def generate(self, writer: "_CodeWriter") -> None:
value = self.value
# Compress whitespace if requested, with a crude heuristic to avoid
# altering preformatted whitespace.
if "<pre>" not in value:
value = filter_whitespace(self.whitespace, value)
if value:
writer.write_line("_tt_append(%r)" % escape.utf8(value), self.line)
| _Text |
python | langchain-ai__langchain | libs/langchain/langchain_classic/evaluation/string_distance/base.py | {
"start": 9682,
"end": 13633
} | class ____(PairwiseStringEvaluator, _RapidFuzzChainMixin):
"""Compute string edit distances between two predictions."""
@property
def input_keys(self) -> list[str]:
"""Get the input keys.
Returns:
The input keys.
"""
return ["prediction", "prediction_b"]
@property
def evaluation_name(self) -> str:
"""Get the evaluation name.
Returns:
The evaluation name.
"""
return f"pairwise_{self.distance.value}_distance"
@override
def _call(
self,
inputs: dict[str, Any],
run_manager: CallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Compute the string distance between two predictions.
Args:
inputs: The input values.
run_manager: The callback manager.
Returns:
The evaluation results containing the score.
"""
return {
"score": self.compute_metric(inputs["prediction"], inputs["prediction_b"]),
}
@override
async def _acall(
self,
inputs: dict[str, Any],
run_manager: AsyncCallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Asynchronously compute the string distance between two predictions.
Args:
inputs: The input values.
run_manager: The callback manager.
Returns:
The evaluation results containing the score.
"""
return {
"score": self.compute_metric(inputs["prediction"], inputs["prediction_b"]),
}
@override
def _evaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate the string distance between two predictions.
Args:
prediction: The first prediction string.
prediction_b: The second prediction string.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run info in the output.
**kwargs: Additional keyword arguments.
Returns:
The evaluation results containing the score.
"""
result = self(
inputs={"prediction": prediction, "prediction_b": prediction_b},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate the string distance between two predictions.
Args:
prediction: The first prediction string.
prediction_b: The second prediction string.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run info in the output.
**kwargs: Additional keyword arguments.
Returns:
The evaluation results containing the score.
"""
result = await self.acall(
inputs={"prediction": prediction, "prediction_b": prediction_b},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
| PairwiseStringDistanceEvalChain |
python | ansible__ansible | lib/ansible/modules/user.py | {
"start": 116556,
"end": 116784
} | class ____(BusyBox):
"""
This is the Alpine User manipulation class. It inherits the BusyBox class
behaviors such as using adduser and deluser commands.
"""
platform = 'Linux'
distribution = 'Alpine'
| Alpine |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/runs_feed.py | {
"start": 1241,
"end": 1498
} | class ____(graphene.ObjectType):
class Meta:
name = "RunsFeedConnection"
results = non_null_list(GrapheneRunsFeedEntry)
cursor = graphene.NonNull(graphene.String)
hasMore = graphene.NonNull(graphene.Boolean)
| GrapheneRunsFeedConnection |
python | ray-project__ray | python/ray/serve/_private/proxy_request_response.py | {
"start": 5750,
"end": 5880
} | class ____:
application_name: str = ""
deployment_name: str = ""
route: str = ""
@dataclass(frozen=True)
| HandlerMetadata |
python | pennersr__django-allauth | allauth/socialaccount/providers/dingtalk/provider.py | {
"start": 223,
"end": 486
} | class ____(ProviderAccount):
def get_avatar_url(self):
return self.account.extra_data.get("avatarUrl")
def to_str(self):
return self.account.extra_data.get(
"nick", super(DingTalkAccount, self).to_str()
)
| DingTalkAccount |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 207218,
"end": 209435
} | class ____(TestCase):
def setUp(self):
self.x = 2 * np.ones((3,), dtype=int)
self.y = 3 * np.ones((3,), dtype=int)
self.x2 = 2 * np.ones((2, 3), dtype=int)
self.y2 = 3 * np.ones((2, 3), dtype=int)
self.ind = [0, 0, 1]
def test_basic(self):
A = np.choose(self.ind, (self.x, self.y))
assert_equal(A, [2, 2, 3])
def test_broadcast1(self):
A = np.choose(self.ind, (self.x2, self.y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
def test_broadcast2(self):
A = np.choose(self.ind, (self.x, self.y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
# XXX: revisit xfails when NEP 50 lands in numpy
@skip(reason="XXX: revisit xfails when NEP 50 lands in numpy")
@parametrize(
"ops",
[
(1000, np.array([1], dtype=np.uint8)),
(-1, np.array([1], dtype=np.uint8)),
(1.0, np.float32(3)),
(1.0, np.array([3], dtype=np.float32)),
],
)
def test_output_dtype(self, ops):
expected_dt = np.result_type(*ops)
assert np.choose([0], ops).dtype == expected_dt
def test_docstring_1(self):
# examples from the docstring,
# https://numpy.org/doc/1.23/reference/generated/numpy.choose.html
choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
A = np.choose([2, 3, 1, 0], choices)
assert_equal(A, [20, 31, 12, 3])
def test_docstring_2(self):
a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
choices = [-10, 10]
A = np.choose(a, choices)
assert_equal(A, [[10, -10, 10], [-10, 10, -10], [10, -10, 10]])
def test_docstring_3(self):
a = np.array([0, 1]).reshape((2, 1, 1))
c1 = np.array([1, 2, 3]).reshape((1, 3, 1))
c2 = np.array([-1, -2, -3, -4, -5]).reshape((1, 1, 5))
A = np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
expected = np.array(
[
[[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3]],
[[-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5]],
]
)
assert_equal(A, expected)
| TestChoose |
python | conda__conda | conda/auxlib/entity.py | {
"start": 19343,
"end": 21097
} | class ____(Field):
_type = tuple
def __init__(self, element_type, default=NULL, required=True, validation=None,
in_dump=True, default_in_dump=True, nullable=False, immutable=False, aliases=()):
self._element_type = element_type
super().__init__(
default, required, validation, in_dump, default_in_dump, nullable, immutable, aliases
)
def box(self, instance, instance_type, val):
if val is None:
return None
elif isinstance(val, str):
raise ValidationError(
f"Attempted to assign a string to ListField {self.name}"
)
elif isiterable(val):
et = self._element_type
if isinstance(et, type) and issubclass(et, Entity):
return self._type(v if isinstance(v, et) else et(**v) for v in val)
else:
return deepfreeze(val) if self.immutable else self._type(val)
else:
raise ValidationError(
val, msg=f"Cannot assign a non-iterable value to {self.name}"
)
def unbox(self, instance, instance_type, val):
return self._type() if val is None and not self.nullable else val
def dump(self, instance, instance_type, val):
if isinstance(self._element_type, type) and issubclass(self._element_type, Entity):
return self._type(v.dump() for v in val)
else:
return val
def validate(self, instance, val):
val = super().validate(instance, val)
if val:
et = self._element_type
self._type(Raise(ValidationError(self.name, el, et)) for el in val
if not isinstance(el, et))
return val
| ListField |
python | allegroai__clearml | clearml/binding/frameworks/__init__.py | {
"start": 1467,
"end": 1559
} | class ____(object):
def __init__(self) -> None:
self.trains_in_model = None
| _Empty |
python | sympy__sympy | sympy/core/logic.py | {
"start": 9653,
"end": 9826
} | class ____(AndOr_Base):
op_x_notx = True
def _eval_propagate_not(self):
# !(a|b|c ...) == !a & !b & !c ...
return And(*[Not(a) for a in self.args])
| Or |
python | numba__numba | numba/core/typeinfer.py | {
"start": 27138,
"end": 28640
} | class ____(object):
def __init__(self, target, attr, value, loc, inst):
self.target = target
self.attr = attr
self.value = value
self.loc = loc
self.inst = inst
def __call__(self, typeinfer):
with new_error_context("typing of get attribute at {loc}",
loc=self.loc):
typevars = typeinfer.typevars
valtys = typevars[self.value.name].get()
for ty in valtys:
attrty = typeinfer.context.resolve_getattr(ty, self.attr)
if attrty is None:
raise UntypedAttributeError(ty, self.attr,
loc=self.inst.loc)
else:
assert attrty.is_precise()
typeinfer.add_type(self.target, attrty, loc=self.loc)
typeinfer.refine_map[self.target] = self
def refine(self, typeinfer, target_type):
if isinstance(target_type, types.BoundFunction):
recvr = target_type.this
assert recvr.is_precise()
typeinfer.add_type(self.value.name, recvr, loc=self.loc)
source_constraint = typeinfer.refine_map.get(self.value.name)
if source_constraint is not None:
source_constraint.refine(typeinfer, recvr)
def __repr__(self):
return 'resolving type of attribute "{attr}" of "{value}"'.format(
value=self.value, attr=self.attr)
| GetAttrConstraint |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2_test.py | {
"start": 141590,
"end": 142635
} | class ____(
VocabularyFileCategoricalColumnTest):
_FILE_FORMAT = 'tfrecord_gzip'
_VOCABULARY_SIZE_ERROR = (errors.FailedPreconditionError,
'Input dataset was expected to contain 4 elements')
def setUp(self):
super(VocabularyTfrecordGzipFileCategoricalColumnTest, self).setUp()
# Contains ints, Golden State Warriors jersey numbers: 30, 35, 11, 23, 22
self._warriors_vocabulary_file_name = test.test_src_dir_path(
'python/feature_column/testdata/warriors_vocabulary.tfrecord.gz')
self._warriors_vocabulary_size = 5
# Contains strings, character names from 'The Wire': omar, stringer, marlo
self._wire_vocabulary_file_name = test.test_src_dir_path(
'python/feature_column/testdata/wire_vocabulary.tfrecord.gz')
self._wire_vocabulary_size = 3
# Contains unicode characters.
self._unicode_vocabulary_file_name = test.test_src_dir_path(
'python/feature_column/testdata/unicode_vocabulary.tfrecord.gz')
| VocabularyTfrecordGzipFileCategoricalColumnTest |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/alignment_containers.py | {
"start": 169,
"end": 562
} | class ____(App[None]):
CSS = """
Center {
tint: $primary 10%;
}
Middle {
tint: $accent 10%;
}
"""
def compose(self) -> ComposeResult:
with Center():
yield Button.success("center")
with Middle():
yield Button.error("middle")
app = AlignContainersApp()
if __name__ == "__main__":
app.run()
| AlignContainersApp |
python | django__django | tests/admin_scripts/configured_dynamic_settings_manage.py | {
"start": 147,
"end": 487
} | class ____:
def __getattr__(self, name):
if name == "FOO":
return "bar"
return getattr(global_settings, name)
def __dir__(self):
return super().__dir__() + dir(global_settings) + ["FOO"]
if __name__ == "__main__":
settings.configure(Settings())
execute_from_command_line(sys.argv)
| Settings |
python | pyinstaller__pyinstaller | tests/functional/modules/pyi_testmod_metapath1/extern/__init__.py | {
"start": 3825,
"end": 4109
} | class ____(VendorImporter):
@property
def search_path(self):
"""
Only search the vendor package, and not a natural package.
"""
yield self.vendor_pkg + '.'
names = ('aaa', 'bbb', 'ccc')
MyVendorImporter(__name__, names).install()
| MyVendorImporter |
python | getlogbook__logbook | src/logbook/more.py | {
"start": 9335,
"end": 9837
} | class ____:
"""A formatter object that makes it easy to format using a Jinja 2
template instead of a format string.
"""
def __init__(self, template):
try:
from jinja2 import Template
except ImportError:
raise RuntimeError("The jinja2 library is required for the JinjaFormatter.")
self.template = Template(template)
def __call__(self, record, handler):
return self.template.render(record=record, handler=handler)
| JinjaFormatter |
python | huggingface__transformers | src/transformers/models/metaclip_2/modular_metaclip_2.py | {
"start": 15377,
"end": 18030
} | class ____(CLIPTextModel):
"""
The text model from MetaClip2 without any head or projection on top.
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.
Args:
config ([`MetaClip2TextConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
Examples:
```python
>>> from transformers import AutoTokenizer, MetaClip2TextModel
>>> model = MetaClip2TextModel.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu")
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
```"""
@check_model_inputs(tie_last_hidden_states=False)
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
):
r"""
Examples:
```python
>>> from transformers import AutoTokenizer, MetaClip2TextModel
>>> model = MetaClip2TextModel.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu")
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
```"""
return super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
**kwargs,
)
| MetaClip2TextModel |
python | pytorch__pytorch | torch/_export/passes/functionalize_side_effectful_ops_pass.py | {
"start": 582,
"end": 3279
} | class ____(_ExportPassBaseDeprecatedDoNotUse):
"""
Functionalize ops with side effect in graph module by replacing the op with
functional version of it. A new dependency token (`dep_token`) will be
created and propagated through functional ops to output.
For example:
```
def f(x):
sym_constrain_range(x.shape[0], min=1, max=3)
return x.add(3)
```
Will be transformed to:
```
def f(x):
dep_token0 = _make_dep_token()
dep_token1 = _functional_sym_constrain_range(
x.shape[0], min=1, max=3, dep_token=dep_token0
)
return x.add(3), dep_token1
```
"""
def __init__(self) -> None:
super().__init__()
self._dep_token: Optional[ProxyValue] = None
self._next_dep_token_index: Optional[int] = None
def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
# Early return if no non-functional assertions.
if not any(
n.target in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS
for n in graph_module.graph.nodes
):
return PassResult(graph_module=graph_module, modified=False)
gm = copy.deepcopy(graph_module)
self._dep_token = None
self._next_dep_token_index = None
return super().call(gm)
def call_operator(
self,
op: OpOverload,
args: tuple[Argument, ...],
kwargs: dict[str, Argument],
meta: NodeMetadata,
) -> ProxyValue:
if op not in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS:
return super().call_operator(op, args, kwargs, meta)
if self._dep_token is None:
self._dep_token = super().call_operator(
aten._make_dep_token,
args=(),
kwargs={},
meta=self._create_dummy_node_metadata(),
)
self._dep_token.node.name = "dep_token0"
self._next_dep_token_index = 1
self._dep_token = super().call_operator(
_NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS[op],
args=args,
kwargs={**kwargs, "dep_token": self._dep_token},
meta=meta,
)
assert self._next_dep_token_index is not None
self._dep_token.node.name = f"dep_token{self._next_dep_token_index}"
self._next_dep_token_index += 1
return self._dep_token
def output(self, results: list[Argument], meta: NodeMetadata) -> ProxyValue:
assert self._dep_token is not None
return super().output(results=(*results, self._dep_token), meta=meta) # type: ignore[arg-type]
| _FunctionalizeSideEffectfulOpsPass |
python | miyuchina__mistletoe | mistletoe/span_token.py | {
"start": 4111,
"end": 4851
} | class ____(SpanToken):
"""
Image token. ("")
This is an inline token. Its children are inline (span) tokens holding the image description.
One of the core tokens.
Attributes:
src (str): image source.
title (str): image title (default to empty).
label (str): link label, for reference links.
"""
repr_attributes = ("src", "title")
def __init__(self, match):
self.src = EscapeSequence.strip(match.group(2).strip())
self.title = EscapeSequence.strip(match.group(3))
self.dest_type = getattr(match, "dest_type", None)
self.label = getattr(match, "label", None)
self.title_delimiter = getattr(match, "title_delimiter", None)
| Image |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 14457,
"end": 14813
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
text_document: TextDocumentIdentifier
@staticmethod
def from_json_rpc_parameters(
parameters: json_rpc.Parameters,
) -> "TypeCoverageParameters":
return _parse_parameters(parameters, target=TypeCoverageParameters)
@dataclasses.dataclass(frozen=True)
| TypeCoverageParameters |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/missingSuper1.py | {
"start": 255,
"end": 295
} | class ____(ParentB):
pass
| ParentBPrime |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 7661,
"end": 7788
} | class ____(VOWarning, SyntaxWarning):
"""
A feature of the VOTABLE_ spec is not implemented.
"""
| UnimplementedWarning |
python | crytic__slither | slither/printers/call/call_graph.py | {
"start": 6599,
"end": 9159
} | class ____(AbstractPrinter):
ARGUMENT = "call-graph"
HELP = "Export the call-graph of the contracts to a dot file"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#call-graph"
def output(self, filename: str) -> Output:
"""
Output the graph in filename
Args:
filename(string)
"""
all_contracts_filename = ""
if not filename.endswith(".dot"):
if filename in ("", "."):
filename = ""
else:
filename += "."
all_contracts_filename = f"{filename}all_contracts.call-graph.dot"
if filename == ".dot":
all_contracts_filename = "all_contracts.dot"
info = ""
results = []
with open(all_contracts_filename, "w", encoding="utf8") as f:
info += f"Call Graph: {all_contracts_filename}\n"
# Avoid duplicate functions due to different compilation unit
all_functionss = [
compilation_unit.functions for compilation_unit in self.slither.compilation_units
]
all_functions = [item for sublist in all_functionss for item in sublist]
all_functions_as_dict = {
function.canonical_name: function for function in all_functions
}
content = "\n".join(
["strict digraph {"]
+ ['rankdir="LR"']
+ ["node [shape=box]"]
+ [_process_functions(list(all_functions_as_dict.values()))]
+ ["}"]
)
f.write(content)
results.append((all_contracts_filename, content))
for derived_contract in self.slither.contracts_derived:
derived_output_filename = f"{filename}{derived_contract.name}.call-graph.dot"
with open(derived_output_filename, "w", encoding="utf8") as f:
info += f"Call Graph: {derived_output_filename}\n"
content = "\n".join(
["strict digraph {"]
+ ['rankdir="LR"']
+ ["node [shape=box]"]
+ [_process_functions(derived_contract.functions)]
+ ["}"]
)
f.write(content)
results.append((derived_output_filename, content))
self.info(info)
res = self.generate_output(info)
for filename_result, content in results:
res.add_file(filename_result, content)
return res
| PrinterCallGraph |
python | pytorch__pytorch | test/export/test_sparse.py | {
"start": 1715,
"end": 2020
} | class ____(torch.nn.Module):
def forward(self, x):
return [xi.to_sparse_csr() for xi in x]
#
# The test driver.
#
@unittest.skipIf(is_fbcode(), "See torch._dynamo.config")
@unittest.skipIf(
sys.version_info >= (3, 12), "torch.compile is not supported on python 3.12+"
)
| SparseActivationCSR |
python | doocs__leetcode | solution/0600-0699/0665.Non-decreasing Array/Solution.py | {
"start": 0,
"end": 492
} | class ____:
def checkPossibility(self, nums: List[int]) -> bool:
def is_sorted(nums: List[int]) -> bool:
return all(a <= b for a, b in pairwise(nums))
n = len(nums)
for i in range(n - 1):
a, b = nums[i], nums[i + 1]
if a > b:
nums[i] = b
if is_sorted(nums):
return True
nums[i] = nums[i + 1] = a
return is_sorted(nums)
return True
| Solution |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_artifacts.py | {
"start": 31835,
"end": 32715
} | class ____:
async def test_delete_artifact_succeeds(self, artifact, session, client):
artifact_id = artifact["id"]
artifact_key = artifact["key"]
response = await client.delete(f"/artifacts/{artifact_id}")
assert response.status_code == 204
artifact = await models.artifacts.read_artifact(
session=session, artifact_id=artifact_id
)
assert artifact is None
assert not await models.artifacts.read_latest_artifact(
session=session,
key=artifact_key,
)
response = await client.get(f"/artifacts/{artifact_id}")
assert response.status_code == 404
async def test_delete_artifact_returns_404_if_does_not_exist(self, client):
response = await client.delete(f"/artifacts/{str(uuid4())}")
assert response.status_code == 404
| TestDeleteArtifact |
python | pennersr__django-allauth | allauth/socialaccount/providers/tiktok/provider.py | {
"start": 288,
"end": 687
} | class ____(ProviderAccount):
def get_username(self):
return self.account.extra_data.get("username")
def get_display_name(self):
return self.account.extra_data.get("display_name")
def get_profile_url(self):
return self.account.extra_data.get("profile_deep_link")
def get_avatar_url(self):
return self.account.extra_data.get("avatar_url")
| TikTokAccount |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/column_pair_map_expectation_template.py | {
"start": 2783,
"end": 5719
} | class ____(ColumnPairMapExpectation):
# </snippet>
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_pair_map_expectation_template.py docstring">
"""TODO: Add a docstring here"""
# </snippet>
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = []
# 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.
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_pair_map_expectation_template.py map_metric">
map_metric = "METRIC NAME GOES HERE"
# </snippet>
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = (
"column_A",
"column_B",
"mostly",
)
def validate_configuration(
self, configuration: Optional[ExpectationConfiguration]
) -> None:
"""
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
None. Raises InvalidExpectationConfigurationError if the config is not validated successfully
"""
super().validate_configuration(configuration)
configuration = configuration or self.configuration
# # Check other things in configuration.kwargs and raise Exceptions if needed
# try:
# assert (
# ...
# ), "message"
# assert (
# ...
# ), "message"
# except AssertionError as e:
# raise InvalidExpectationConfigurationError(str(e))
# This object contains metadata for display in the public Gallery
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_pair_map_expectation_template.py library_metadata">
library_metadata = {
"tags": [], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@your_name_here", # Don't forget to add your github handle here!
],
}
# </snippet>
if __name__ == "__main__":
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_pair_map_expectation_template.py diagnostics">
ExpectColumnPairValuesToMatchSomeCriteria().print_diagnostic_checklist()
# </snippet>
| ExpectColumnPairValuesToMatchSomeCriteria |
python | xlwings__xlwings | xlwings/pro/_xlremote.py | {
"start": 39280,
"end": 42285
} | class ____(base_classes.Font):
# TODO: support Shape and getters
def __init__(self, parent, api):
self.parent = parent
self._api = api
def append_json_action(self, **kwargs):
if isinstance(self.parent, Range):
self.parent.append_json_action(
**{
**kwargs,
}
)
else:
raise NotImplementedError()
@property
def api(self):
return self._api
@property
def bold(self):
raise NotImplementedError()
@bold.setter
def bold(self, value):
self.append_json_action(func="setFontProperty", args=["bold", value])
@property
def italic(self):
raise NotImplementedError()
@italic.setter
def italic(self, value):
self.append_json_action(func="setFontProperty", args=["italic", value])
@property
def size(self):
raise NotImplementedError()
@size.setter
def size(self, value):
self.append_json_action(func="setFontProperty", args=["size", value])
@property
def color(self):
raise NotImplementedError()
@color.setter
def color(self, color_or_rgb):
if not isinstance(color_or_rgb, str):
raise ValueError('Color must be supplied in hex format e.g., "#FFA500".')
self.append_json_action(func="setFontProperty", args=["color", color_or_rgb])
@property
def name(self):
raise NotImplementedError()
@name.setter
def name(self, value):
self.append_json_action(func="setFontProperty", args=["name", value])
if __name__ == "__main__":
# python -m xlwings.pro._xlremote
import inspect
def print_unimplemented_attributes(class_name, base_class, derived_class=None):
if class_name == "Apps":
return
base_attributes = set(
attr
for attr in vars(base_class)
if not (attr.startswith("_") or attr == "api")
)
if derived_class:
derived_attributes = set(
attr for attr in vars(derived_class) if not attr.startswith("_")
)
else:
derived_attributes = set()
unimplemented_attributes = base_attributes - derived_attributes
if unimplemented_attributes:
print("")
print(f" xlwings.{class_name}")
print("")
for attribute in unimplemented_attributes:
if not attribute.startswith("__") and attribute not in (
"api",
"xl",
"hwnd",
):
if callable(getattr(base_class, attribute)):
print(f" - {attribute}()")
else:
print(f" - {attribute}")
for name, obj in inspect.getmembers(base_classes):
if inspect.isclass(obj):
print_unimplemented_attributes(name, obj, globals().get(name))
| Font |
python | sphinx-doc__sphinx | sphinx/ext/autosummary/generate.py | {
"start": 2131,
"end": 2883
} | class ____:
"""Dummy Application class for sphinx-autogen command."""
def __init__(self, translator: NullTranslations) -> None:
self.config = Config()
self.events = _DummyEvents()
self.registry = SphinxComponentRegistry()
self.messagelog: list[str] = []
self.srcdir = _StrPath('/')
self.translator = translator
self.verbosity = 0
self._warncount = 0
self._exception_on_warning = False
self.config.add('autosummary_context', {}, 'env', ())
self.config.add('autosummary_filename_map', {}, 'env', ())
self.config.add('autosummary_ignore_module_all', True, 'env', bool)
def emit_firstresult(self, *args: Any) -> None:
pass
| DummyApplication |
python | mlflow__mlflow | mlflow/store/artifact/cloud_artifact_repo.py | {
"start": 3105,
"end": 13307
} | class ____(ArtifactRepository):
def __init__(
self, artifact_uri: str, tracking_uri: str | None = None, registry_uri: str | None = None
) -> None:
super().__init__(artifact_uri, tracking_uri, registry_uri)
# Use an isolated thread pool executor for chunk uploads/downloads to avoid a deadlock
# caused by waiting for a chunk-upload/download task within a file-upload/download task.
# See https://superfastpython.com/threadpoolexecutor-deadlock/#Deadlock_1_Submit_and_Wait_for_a_Task_Within_a_Task
# for more details
self.chunk_thread_pool = self._create_thread_pool()
# Write APIs
def log_artifacts(self, local_dir, artifact_path=None):
"""
Parallelized implementation of `log_artifacts`.
"""
artifact_path = artifact_path or ""
staged_uploads = []
for dirpath, _, filenames in os.walk(local_dir):
artifact_subdir = artifact_path
if dirpath != local_dir:
rel_path = os.path.relpath(dirpath, local_dir)
rel_path = relative_path_to_artifact_path(rel_path)
artifact_subdir = posixpath.join(artifact_path, rel_path)
for name in filenames:
src_file_path = os.path.join(dirpath, name)
src_file_name = os.path.basename(src_file_path)
staged_uploads.append(
StagedArtifactUpload(
src_file_path=src_file_path,
artifact_file_path=posixpath.join(artifact_subdir, src_file_name),
)
)
# Join futures to ensure that all artifacts have been uploaded prior to returning
failed_uploads = {}
# For each batch of files, upload them in parallel and wait for completion
# TODO: change to class method
def upload_artifacts_iter():
for staged_upload_chunk in chunk_list(staged_uploads, _ARTIFACT_UPLOAD_BATCH_SIZE):
write_credential_infos = self._get_write_credential_infos(
remote_file_paths=[
staged_upload.artifact_file_path for staged_upload in staged_upload_chunk
],
)
inflight_uploads = {}
for staged_upload, write_credential_info in zip(
staged_upload_chunk, write_credential_infos
):
upload_future = self.thread_pool.submit(
self._upload_to_cloud,
cloud_credential_info=write_credential_info,
src_file_path=staged_upload.src_file_path,
artifact_file_path=staged_upload.artifact_file_path,
)
inflight_uploads[staged_upload.src_file_path] = upload_future
yield from inflight_uploads.items()
with ArtifactProgressBar.files(
desc="Uploading artifacts", total=len(staged_uploads)
) as pbar:
for src_file_path, upload_future in upload_artifacts_iter():
try:
upload_future.result()
pbar.update()
except Exception as e:
failed_uploads[src_file_path] = repr(e)
if len(failed_uploads) > 0:
raise MlflowException(
message=(
"The following failures occurred while uploading one or more artifacts"
f" to {self.artifact_uri}: {failed_uploads}"
)
)
@abstractmethod
def _get_write_credential_infos(self, remote_file_paths):
"""
Retrieve write credentials for a batch of remote file paths, including presigned URLs.
Args:
remote_file_paths: List of file paths in the remote artifact repository.
Returns:
List of ArtifactCredentialInfo objects corresponding to each file path.
"""
@abstractmethod
def _upload_to_cloud(self, cloud_credential_info, src_file_path, artifact_file_path):
"""
Upload a single file to the cloud.
Args:
cloud_credential_info: ArtifactCredentialInfo object with presigned URL for the file.
src_file_path: Local source file path for the upload.
artifact_file_path: Path in the artifact repository where the artifact will be logged.
"""
# Read APIs
def _extract_headers_from_credentials(self, headers):
"""
Returns:
A python dictionary of http headers converted from the protobuf credentials.
"""
return {header.name: header.value for header in headers}
def _parallelized_download_from_cloud(self, file_size, remote_file_path, local_path):
read_credentials = self._get_read_credential_infos([remote_file_path])
# Read credentials for only one file were requested. So we expected only one value in
# the response.
assert len(read_credentials) == 1
cloud_credential_info = read_credentials[0]
with remove_on_error(local_path):
parallel_download_subproc_env = os.environ.copy()
failed_downloads = parallelized_download_file_using_http_uri(
thread_pool_executor=self.chunk_thread_pool,
http_uri=cloud_credential_info.signed_uri,
download_path=local_path,
remote_file_path=remote_file_path,
file_size=file_size,
uri_type=cloud_credential_info.type,
chunk_size=MLFLOW_MULTIPART_DOWNLOAD_CHUNK_SIZE.get(),
env=parallel_download_subproc_env,
headers=self._extract_headers_from_credentials(cloud_credential_info.headers),
)
num_retries = _MLFLOW_MPD_NUM_RETRIES.get()
interval = _MLFLOW_MPD_RETRY_INTERVAL_SECONDS.get()
failed_downloads = list(failed_downloads)
while failed_downloads and num_retries > 0:
self._refresh_credentials()
new_cloud_creds = self._get_read_credential_infos([remote_file_path])[0]
new_signed_uri = new_cloud_creds.signed_uri
new_headers = self._extract_headers_from_credentials(new_cloud_creds.headers)
futures = {
self.chunk_thread_pool.submit(
download_chunk,
range_start=chunk.start,
range_end=chunk.end,
headers=new_headers,
download_path=local_path,
http_uri=new_signed_uri,
): chunk
for chunk in failed_downloads
}
new_failed_downloads = []
for future in as_completed(futures):
chunk = futures[future]
try:
future.result()
except Exception as e:
_logger.info(
f"Failed to download chunk {chunk.index} for {chunk.path}: {e}. "
f"The download of this chunk will be retried later."
)
new_failed_downloads.append(chunk)
failed_downloads = new_failed_downloads
num_retries -= 1
time.sleep(interval)
if failed_downloads:
raise MlflowException(
message=("All retries have been exhausted. Download has failed.")
)
def _download_file(self, remote_file_path, local_path):
# list_artifacts API only returns a list of FileInfos at the specified path
# if it's a directory. To get file size, we need to iterate over FileInfos
# contained by the parent directory. A bad path could result in there being
# no matching FileInfos (by path), so fall back to None size to prevent
# parallelized download.
parent_dir = posixpath.dirname(remote_file_path)
file_infos = self.list_artifacts(parent_dir)
file_info = [info for info in file_infos if info.path == remote_file_path]
file_size = file_info[0].file_size if len(file_info) == 1 else None
# NB: FUSE mounts do not support file write from a non-0th index seek position.
# Due to this limitation (writes must start at the beginning of a file),
# offset writes are disabled if FUSE is the local_path destination.
if (
not MLFLOW_ENABLE_MULTIPART_DOWNLOAD.get()
or not file_size
or file_size < MLFLOW_MULTIPART_DOWNLOAD_MINIMUM_FILE_SIZE.get()
or is_fuse_or_uc_volumes_uri(local_path)
# DatabricksSDKModelsArtifactRepository can only download file via databricks sdk
# rather than presigned uri used in _parallelized_download_from_cloud.
or type(self).__name__ == "DatabricksSDKModelsArtifactRepository"
):
self._download_from_cloud(remote_file_path, local_path)
else:
self._parallelized_download_from_cloud(file_size, remote_file_path, local_path)
@abstractmethod
def _get_read_credential_infos(self, remote_file_paths):
"""
Retrieve read credentials for a batch of remote file paths, including presigned URLs.
Args:
remote_file_paths: List of file paths in the remote artifact repository.
Returns:
List of ArtifactCredentialInfo objects corresponding to each file path.
"""
@abstractmethod
def _download_from_cloud(self, remote_file_path, local_path):
"""
Download a file from the input `remote_file_path` and save it to `local_path`.
Args:
remote_file_path: Path to file in the remote artifact repository.
local_path: Local path to download file to.
"""
def _refresh_credentials(self):
"""
Refresh credentials for user in the case of credential expiration
Args:
None
"""
| CloudArtifactRepository |
python | celery__celery | celery/exceptions.py | {
"start": 3948,
"end": 4056
} | class ____(CeleryWarning):
"""send_task ignores :setting:`task_always_eager` option."""
| AlwaysEagerIgnored |
python | joke2k__faker | faker/providers/address/hi_IN/__init__.py | {
"start": 45,
"end": 4764
} | class ____(AddressProvider):
city_formats = ("{{city_name}}",)
street_name_formats = (
"{{first_name}} {{last_name}}",
"{{last_name}}",
)
street_address_formats = ("{{building_number}} {{street_name}}",)
address_formats = (
"{{street_address}}\n{{city}} {{postcode}}",
"{{street_address}}\n{{city}}-{{postcode}}",
)
building_number_formats = (
"####",
"###",
"##",
"#",
"#/#",
"##/##",
"##/###",
"##/####",
)
postcode_formats = ("######",)
cities = (
"आदिलाबाद",
"अगरतला",
"अहमदाबाद",
"अहमदनगर",
"अजमेर",
"अम्बाजी",
"अमरपुर",
"इलाहाबाद",
"अकोला",
"अखनूर",
"अन्तर्गत",
"अलांग",
"अलीगढ",
"दादरा और नगर हवेली",
"अमरावती",
"अमरोहा",
"अनन्तपुर",
"करना",
"जिससेबेलारी",
"अनंतनाग",
"भागलपुर",
"भद्रक",
"बचेली",
"बहादुरगंज",
"बहादुरगढ",
"चिरमिरी",
"चिराला",
"चित्रदुर्ग",
"चित्तूर",
"चित्रकूट",
"देवगढ़",
"दालखोला",
"देवास",
"चंडीगढ",
"चिपलुन",
"चक्रधरपुर",
"चंबा",
"फतहपुर",
"फतेहपुर",
"फतेहगढ",
"सभापतिने",
"देवगढ़",
"धर्मापुरी",
"पाकाला",
"धारवाड",
"असम",
"देहरा",
"रानीताल",
"खडगपुर",
"मोकामा",
"मोकोकचुंग",
"जिलोंपर",
"विस्तारण",
"मोतिहारी",
"लखनऊ",
"मुंबई",
"हैदराबाद",
)
states = (
"अरूणाचल प्रदेश",
"बिहार",
"असम",
"आंध्र प्रदेश",
"छत्तीसगढ",
"हरियाणा",
"गुजरात",
"हिमाचल प्रदेश",
"गोवा",
"मध्य प्रदेश",
"महाराष्ट्र",
"जम्मू और कश्मीर",
"केरल",
"कर्नाटक",
"मणिपुर",
"मिजोरम",
"मेघालय",
"सिक्किम",
"राजस्थान",
"पंजाब",
"उडीसा",
"उत्तरांचल",
"उत्तर प्रदेश",
"तमिलनाडु",
"त्रिपुरा",
"पश्चिमी बंगाल",
"अंडमान और निकोबार",
"दमन और दीव",
"दादरा और नगर हवेली",
"दिल्ली",
"पांडिचेरी",
"लक्षद्वीप",
)
countries = (
"आर्मीनिया",
"यू.के.",
"फ्रांस",
"फलस्तीन",
"मिस्र",
"ब्राज़ील",
"ईरान",
"यूनान",
"स्पेन",
"जॉर्जिया",
"लेबनान",
"सायप्रस",
"सीरिया",
"कनाडा",
"रूस",
"संयुक्त राज्य अमरीका",
"नेदर्लान्ड",
"ऑस्ट्रेलिया",
"एंटीगुआ",
"बार्बुडा",
"ऑस्ट्रिया",
"अज़रबाइजान",
"बारबाडोस",
"बेलारूस",
"बेल्जियम",
"बेलीज़",
"बेनिन",
"बहामास",
"बहरीन",
"बांग्लादेश",
"भूटान",
"बोलिविया",
"बोस्निया",
"हर्जेगोविना",
"बोत्सवाना",
"ब्रुनेई",
"बुल्गारिया",
"बुर्किना फ़ासो",
"बर्मा",
"बुरूंडी",
"डोमिनिकन रिपब्लिक",
"गिनिया",
"टीमोर",
"फ़िनलैंड",
"गेबोन",
"गाम्बिया",
"जर्मनी",
"ग्रेनेडा",
"घाना",
"ग्रेट ब्रिटेन",
"हंगरी",
"भारत",
"हिन्दुस्तान",
"इराक",
"आयरलैंड",
"इंडोनेशिया",
"इटली",
"जमैका",
"जॉर्डन",
"जापान",
"क़जाख़स्तान",
"केन्या",
"किरिबाती",
"दक्षिण कोरिया",
"लातविया",
"लाओस",
"उत्तर कोरिया",
"कोसोवो",
"कुवैत",
"लेबनान",
"लिचटीनस्टीन",
"लिथुआनिया",
"लक्समबर्ग",
"लीबिया",
"लाइबेरिया",
"लेसोथो",
"नेपाल",
"न्यूज़ीलैण्ड",
"निकारागुआ",
"नाइजर",
"नाउरू",
"सेंट लुसिया",
"रोमानिया",
"अरब अमीरात",
"यूएई",
"युगांडा",
"यूक्रेन",
"उरूग्वे",
"उज़बेकिस्तान",
"यूनाइटेड किंगडम",
"वानुआतू",
"वेटिकन सिटी",
"वेनेजुएला",
"पश्चिमी सहारा",
"वियतनाम",
"यमन",
"ज़ायर",
"ज़ाम्बिया",
"ज़िम्बाब्वे",
"पाकिस्तान",
"सउदी अरब",
"ओमान",
"क़तर",
"ट्यूनीशिया",
"मोरक्को",
"तुर्की",
"श्रीलंका",
"अफ़ग़ानिस्तान",
)
def city_name(self) -> str:
return self.random_element(self.cities)
def administrative_unit(self) -> str:
return self.random_element(self.states)
state = administrative_unit
| Provider |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 15791,
"end": 15905
} | class ____(BaseModel):
len: int
type: Literal["XComLengthResponse"] = "XComLengthResponse"
| XComCountResponse |
python | davidhalter__jedi | test/completion/arrays.py | {
"start": 838,
"end": 1991
} | class ____:
def __getitem__(self, item):
return item
#?
Foo()[:, :-1][0]
# -----------------
# iterable multiplication
# -----------------
a = ['']*2
#? list()
a
# -----------------
# tuple assignments
# -----------------
a1, b1 = (1, "")
#? int()
a1
#? str()
b1
(a2, b2) = (1, "")
#? int()
a2
#? str()
b2
# list assignment
[list1, list2] = (1, "")
#? int()
list1
#? str()
list2
[list3, list4] = [1, ""]
#? int()
list3
#? str()
list4
# -----------------
# subtuple assignment
# -----------------
(a3, (b3, c3)) = (1, ("", list))
#? list
c3
a4, (b4, c4) = (1, ("", list))
#? list
c4
#? int()
a4
#? str()
b4
# -----------------
# multiple assignments
# -----------------
a = b = 1
#? int()
a
#? int()
b
(a, b) = (c, (e, f)) = ('2', (3, 4))
#? str()
a
#? tuple()
b
#? str()
c
#? int()
e
#? int()
f
# -----------------
# unnessecary braces
# -----------------
a = (1)
#? int()
a
#? int()
(1)
#? int()
((1))
#? int()
((1)+1)
u, v = 1, ""
#? int()
u
((u1, v1)) = 1, ""
#? int()
u1
#? int()
(u1)
(a), b = 1, ''
#? int()
a
def a(): return ''
#? str()
(a)()
#? str()
(a)().title()
#? int()
(tuple).index()
#? int()
(tuple)().index()
| Foo |
python | kamyu104__LeetCode-Solutions | Python/partition-array-into-three-parts-with-equal-sum.py | {
"start": 29,
"end": 420
} | class ____(object):
def canThreePartsEqualSum(self, A):
"""
:type A: List[int]
:rtype: bool
"""
total = sum(A)
if total % 3 != 0:
return False
parts, curr = 0, 0
for x in A:
curr += x
if curr == total//3:
parts += 1
curr = 0
return parts >= 3
| Solution |
python | django__django | tests/postgres_tests/test_trigram.py | {
"start": 445,
"end": 5780
} | class ____(PostgreSQLTestCase):
Model = CharFieldModel
@classmethod
def setUpTestData(cls):
cls.Model.objects.bulk_create(
[
cls.Model(field="Matthew"),
cls.Model(field="Cat sat on mat."),
cls.Model(field="Dog sat on rug."),
]
)
def test_trigram_search(self):
self.assertQuerySetEqual(
self.Model.objects.filter(field__trigram_similar="Mathew"),
["Matthew"],
transform=lambda instance: instance.field,
)
def test_trigram_word_search(self):
obj = self.Model.objects.create(
field="Gumby rides on the path of Middlesbrough",
)
self.assertSequenceEqual(
self.Model.objects.filter(field__trigram_word_similar="Middlesborough"),
[obj],
)
self.assertSequenceEqual(
self.Model.objects.filter(field__trigram_word_similar="Middle"),
[obj],
)
def test_trigram_strict_word_search_matched(self):
obj = self.Model.objects.create(
field="Gumby rides on the path of Middlesbrough",
)
self.assertSequenceEqual(
self.Model.objects.filter(
field__trigram_strict_word_similar="Middlesborough"
),
[obj],
)
self.assertSequenceEqual(
self.Model.objects.filter(field__trigram_strict_word_similar="Middle"),
[],
)
def test_trigram_similarity(self):
search = "Bat sat on cat."
# Round result of similarity because PostgreSQL uses greater precision.
self.assertQuerySetEqual(
self.Model.objects.filter(
field__trigram_similar=search,
)
.annotate(similarity=TrigramSimilarity("field", search))
.order_by("-similarity"),
[("Cat sat on mat.", 0.625), ("Dog sat on rug.", 0.333333)],
transform=lambda instance: (instance.field, round(instance.similarity, 6)),
ordered=True,
)
def test_trigram_word_similarity(self):
search = "mat"
self.assertSequenceEqual(
self.Model.objects.filter(
field__trigram_word_similar=search,
)
.annotate(
word_similarity=TrigramWordSimilarity(search, "field"),
)
.values("field", "word_similarity")
.order_by("-word_similarity"),
[
{"field": "Cat sat on mat.", "word_similarity": 1.0},
{"field": "Matthew", "word_similarity": 0.75},
],
)
def test_trigram_strict_word_similarity(self):
search = "matt"
self.assertSequenceEqual(
self.Model.objects.filter(field__trigram_word_similar=search)
.annotate(word_similarity=TrigramStrictWordSimilarity(search, "field"))
.values("field", "word_similarity")
.order_by("-word_similarity"),
[
{"field": "Cat sat on mat.", "word_similarity": 0.5},
{"field": "Matthew", "word_similarity": 0.44444445},
],
)
def test_trigram_similarity_alternate(self):
# Round result of distance because PostgreSQL uses greater precision.
self.assertQuerySetEqual(
self.Model.objects.annotate(
distance=TrigramDistance("field", "Bat sat on cat."),
)
.filter(distance__lte=0.7)
.order_by("distance"),
[("Cat sat on mat.", 0.375), ("Dog sat on rug.", 0.666667)],
transform=lambda instance: (instance.field, round(instance.distance, 6)),
ordered=True,
)
def test_trigram_word_similarity_alternate(self):
self.assertSequenceEqual(
self.Model.objects.annotate(
word_distance=TrigramWordDistance("mat", "field"),
)
.filter(
word_distance__lte=0.7,
)
.values("field", "word_distance")
.order_by("word_distance"),
[
{"field": "Cat sat on mat.", "word_distance": 0},
{"field": "Matthew", "word_distance": 0.25},
],
)
def test_trigram_strict_word_distance(self):
self.assertSequenceEqual(
self.Model.objects.annotate(
word_distance=TrigramStrictWordDistance("matt", "field"),
)
.filter(word_distance__lte=0.7)
.values("field", "word_distance")
.order_by("word_distance"),
[
{"field": "Cat sat on mat.", "word_distance": 0.5},
{"field": "Matthew", "word_distance": 0.5555556},
],
)
def test_trigram_concat_precedence(self):
search_term = "im matthew"
self.assertSequenceEqual(
self.Model.objects.annotate(
concat_result=Concat(
Value("I'm "),
F("field"),
output_field=self.Model._meta.get_field("field"),
),
)
.filter(concat_result__trigram_similar=search_term)
.values("field"),
[{"field": "Matthew"}],
)
| TrigramTest |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/benchmarks/utils.py | {
"start": 5041,
"end": 6262
} | class ____:
"""Information about the hardware used to run the query."""
gpus: list[GPUInfo]
# TODO: ucx
@classmethod
def collect(cls) -> HardwareInfo:
"""Collect the hardware information."""
if pynvml is not None:
pynvml.nvmlInit()
gpus = [GPUInfo.from_index(i) for i in range(pynvml.nvmlDeviceGetCount())]
else:
# No GPUs -- probably running in CPU mode
gpus = []
return cls(gpus=gpus)
def _infer_scale_factor(name: str, path: str | Path, suffix: str) -> int | float:
if "pdsh" in name:
supplier = get_data(path, "supplier", suffix)
num_rows = supplier.select(pl.len()).collect().item(0, 0)
return num_rows / 10_000
elif "pdsds" in name:
# TODO: Keep a map of SF-row_count because of nonlinear scaling
# See: https://www.tpc.org/TPC_Documents_Current_Versions/pdf/TPC-DS_v4.0.0.pdf pg.46
customer = get_data(path, "promotion", suffix)
num_rows = customer.select(pl.len()).collect().item(0, 0)
return num_rows / 300
else:
raise ValueError(f"Invalid benchmark script name: '{name}'.")
@dataclasses.dataclass(kw_only=True)
| HardwareInfo |
python | apache__airflow | providers/google/tests/unit/google/marketing_platform/operators/test_search_ads.py | {
"start": 1226,
"end": 2346
} | class ____:
@mock.patch(
"airflow.providers.google.marketing_platform.operators.search_ads.GoogleSearchAdsReportingHook"
)
@mock.patch("airflow.providers.google.marketing_platform.operators.search_ads.BaseOperator")
def test_execute(self, mock_base_op, hook_mock):
query = "SELECT * FROM campaigns WHERE segments.date DURING LAST_30_DAYS"
hook_mock.return_value.search.return_value = {"results": []}
op = GoogleSearchAdsSearchOperator(
customer_id=CUSTOMER_ID,
query=query,
api_version=API_VERSION,
task_id="test_task",
)
op.execute(context=None)
hook_mock.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
api_version="v0",
)
hook_mock.return_value.search.assert_called_once_with(
customer_id=CUSTOMER_ID,
query=query,
page_size=10000,
page_token=None,
return_total_results_count=False,
summary_row_setting=None,
validate_only=False,
)
| TestGoogleSearchAdsSearchOperator |
python | ray-project__ray | python/ray/train/torch/torch_checkpoint.py | {
"start": 520,
"end": 6254
} | class ____(FrameworkCheckpoint):
"""A :class:`~ray.train.Checkpoint` with Torch-specific functionality."""
MODEL_FILENAME = "model.pt"
@classmethod
def from_state_dict(
cls,
state_dict: Dict[str, Any],
*,
preprocessor: Optional["Preprocessor"] = None,
) -> "TorchCheckpoint":
"""Create a :class:`~ray.train.Checkpoint` that stores a model state dictionary.
.. tip::
This is the recommended method for creating
:class:`TorchCheckpoints<TorchCheckpoint>`.
Args:
state_dict: The model state dictionary to store in the checkpoint.
preprocessor: A fitted preprocessor to be applied before inference.
Returns:
A :class:`TorchCheckpoint` containing the specified state dictionary.
Examples:
.. testcode::
import torch
import torch.nn as nn
from ray.train.torch import TorchCheckpoint
# Set manual seed
torch.manual_seed(42)
# Function to create a NN model
def create_model() -> nn.Module:
model = nn.Sequential(nn.Linear(1, 10),
nn.ReLU(),
nn.Linear(10,1))
return model
# Create a TorchCheckpoint from our model's state_dict
model = create_model()
checkpoint = TorchCheckpoint.from_state_dict(model.state_dict())
# Now load the model from the TorchCheckpoint by providing the
# model architecture
model_from_chkpt = checkpoint.get_model(create_model())
# Assert they have the same state dict
assert str(model.state_dict()) == str(model_from_chkpt.state_dict())
print("worked")
.. testoutput::
:hide:
...
"""
tempdir = tempfile.mkdtemp()
model_path = Path(tempdir, cls.MODEL_FILENAME).as_posix()
stripped_state_dict = consume_prefix_in_state_dict_if_present_not_in_place(
state_dict, "module."
)
torch.save(stripped_state_dict, model_path)
checkpoint = cls.from_directory(tempdir)
if preprocessor:
checkpoint.set_preprocessor(preprocessor)
return checkpoint
@classmethod
def from_model(
cls,
model: torch.nn.Module,
*,
preprocessor: Optional["Preprocessor"] = None,
) -> "TorchCheckpoint":
"""Create a :class:`~ray.train.Checkpoint` that stores a Torch model.
.. note::
PyTorch recommends storing state dictionaries. To create a
:class:`TorchCheckpoint` from a state dictionary, call
:meth:`~ray.train.torch.TorchCheckpoint.from_state_dict`. To learn more
about state dictionaries, read
`Saving and Loading Models <https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict>`_. # noqa: E501
Args:
model: The Torch model to store in the checkpoint.
preprocessor: A fitted preprocessor to be applied before inference.
Returns:
A :class:`TorchCheckpoint` containing the specified model.
Examples:
.. testcode::
from ray.train.torch import TorchCheckpoint
import torch
# Create model identity and send a random tensor to it
model = torch.nn.Identity()
input = torch.randn(2, 2)
output = model(input)
# Create a checkpoint
checkpoint = TorchCheckpoint.from_model(model)
print(checkpoint)
.. testoutput::
:hide:
...
"""
tempdir = tempfile.mkdtemp()
model_path = Path(tempdir, cls.MODEL_FILENAME).as_posix()
torch.save(model, model_path)
checkpoint = cls.from_directory(tempdir)
if preprocessor:
checkpoint.set_preprocessor(preprocessor)
return checkpoint
def get_model(self, model: Optional[torch.nn.Module] = None) -> torch.nn.Module:
"""Retrieve the model stored in this checkpoint.
Args:
model: If the checkpoint contains a model state dict, and not
the model itself, then the state dict will be loaded to this
``model``. Otherwise, the model will be discarded.
"""
with self.as_directory() as tempdir:
model_path = Path(tempdir, self.MODEL_FILENAME).as_posix()
if not os.path.exists(model_path):
raise RuntimeError(
"`model.pt` not found within this checkpoint. Make sure you "
"created this `TorchCheckpoint` from one of its public "
"constructors (`from_state_dict` or `from_model`)."
)
model_or_state_dict = torch.load(model_path, map_location="cpu")
if isinstance(model_or_state_dict, torch.nn.Module):
if model:
warnings.warn(
"TorchCheckpoint already contains all information needed. "
"Discarding provided `model` argument. If you are using "
"TorchPredictor directly, you should do "
"`TorchPredictor.from_checkpoint(checkpoint)` by removing kwargs "
"`model=`."
)
model = load_torch_model(
saved_model=model_or_state_dict, model_definition=model
)
return model
| TorchCheckpoint |
python | nedbat__coveragepy | coverage/debug.py | {
"start": 12140,
"end": 12523
} | class ____:
"""A class to add cwd info to debug messages."""
def __init__(self) -> None:
self.cwd: str | None = None
def filter(self, text: str) -> str:
"""Add a cwd message for each new cwd."""
cwd = os.getcwd()
if cwd != self.cwd:
text = f"cwd is now {cwd!r}\n{text}"
self.cwd = cwd
return text
| CwdTracker |
python | kamyu104__LeetCode-Solutions | Python/find-if-array-can-be-sorted.py | {
"start": 671,
"end": 1144
} | class ____(object):
def canSortArray(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def popcount(x):
return bin(x).count("1")
def pairwise(it):
a, b = tee(it)
next(b, None)
return itertools.izip(a, b)
return all(max(a) <= min(b) for a, b in pairwise(list(it) for key, it in groupby(nums, popcount)))
# Time: O(nlogn)
# Space: O(n)
# sort
| Solution2 |
python | walkccc__LeetCode | solutions/15. 3Sum/15.py | {
"start": 0,
"end": 792
} | class ____:
def threeSum(self, nums: list[int]) -> list[list[int]]:
if len(nums) < 3:
return []
ans = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
# Choose nums[i] as the first number in the triplet, then search the
# remaining numbers in [i + 1, n - 1].
l = i + 1
r = len(nums) - 1
while l < r:
summ = nums[i] + nums[l] + nums[r]
if summ == 0:
ans.append((nums[i], nums[l], nums[r]))
l += 1
r -= 1
while nums[l] == nums[l - 1] and l < r:
l += 1
while nums[r] == nums[r + 1] and l < r:
r -= 1
elif summ < 0:
l += 1
else:
r -= 1
return ans
| Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 75108,
"end": 76567
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"repository_id",
"name",
"head_sha",
"details_url",
"external_id",
"status",
"started_at",
"conclusion",
"completed_at",
"output",
"actions",
"client_mutation_id",
)
repository_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="repositoryId"
)
name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name")
head_sha = sgqlc.types.Field(
sgqlc.types.non_null(GitObjectID), graphql_name="headSha"
)
details_url = sgqlc.types.Field(URI, graphql_name="detailsUrl")
external_id = sgqlc.types.Field(String, graphql_name="externalId")
status = sgqlc.types.Field(RequestableCheckStatusState, graphql_name="status")
started_at = sgqlc.types.Field(DateTime, graphql_name="startedAt")
conclusion = sgqlc.types.Field(CheckConclusionState, graphql_name="conclusion")
completed_at = sgqlc.types.Field(DateTime, graphql_name="completedAt")
output = sgqlc.types.Field(CheckRunOutput, graphql_name="output")
actions = sgqlc.types.Field(
sgqlc.types.list_of(sgqlc.types.non_null(CheckRunAction)),
graphql_name="actions",
)
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| CreateCheckRunInput |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 20052,
"end": 23683
} | class ____(PreTrainedModel):
config: DFineConfig
base_model_prefix = "d_fine"
main_input_name = "pixel_values"
input_modalities = ("image",)
_no_split_modules = [r"DFineHybridEncoder", r"DFineDecoderLayer"]
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
# initialize linear layer bias value according to a given probability value.
if isinstance(module, (DFineForObjectDetection, DFineDecoder)):
if module.class_embed is not None:
for layer in module.class_embed:
prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
bias = float(-math.log((1 - prior_prob) / prior_prob))
init.xavier_uniform_(layer.weight)
init.constant_(layer.bias, bias)
if module.bbox_embed is not None:
for layer in module.bbox_embed:
init.constant_(layer.layers[-1].weight, 0)
init.constant_(layer.layers[-1].bias, 0)
if hasattr(module, "reg_scale"):
init.constant_(module.reg_scale, self.config.reg_scale)
if hasattr(module, "up"):
init.constant_(module.up, self.config.up)
if isinstance(module, DFineMultiscaleDeformableAttention):
init.constant_(module.sampling_offsets.weight, 0.0)
default_dtype = torch.get_default_dtype()
thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
2.0 * math.pi / module.n_heads
)
grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
grid_init = grid_init / grid_init.abs().max(-1, keepdim=True).values
grid_init = grid_init.reshape(module.n_heads, 1, 2).tile([1, sum(module.num_points_list), 1])
scaling = torch.concat([torch.arange(1, n + 1) for n in module.num_points_list]).reshape(1, -1, 1)
grid_init *= scaling
init.copy_(module.sampling_offsets.bias, grid_init.flatten())
init.constant_(module.attention_weights.weight, 0.0)
init.constant_(module.attention_weights.bias, 0.0)
if isinstance(module, DFineModel):
prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
bias = float(-math.log((1 - prior_prob) / prior_prob))
init.xavier_uniform_(module.enc_score_head.weight)
init.constant_(module.enc_score_head.bias, bias)
if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
init.zeros_(module.bias)
if isinstance(module, DFineGate):
bias = float(-math.log((1 - 0.5) / 0.5))
init.constant_(module.gate.bias, bias)
init.constant_(module.gate.weight, 0)
if isinstance(module, DFineLQE):
init.constant_(module.reg_conf.layers[-1].bias, 0)
init.constant_(module.reg_conf.layers[-1].weight, 0)
if isinstance(module, nn.LayerNorm):
init.ones_(module.weight)
init.zeros_(module.bias)
if hasattr(module, "weight_embedding") and self.config.learn_initial_query:
init.xavier_uniform_(module.weight_embedding.weight)
if hasattr(module, "denoising_class_embed") and self.config.num_denoising > 0:
init.xavier_uniform_(module.denoising_class_embed.weight)
| DFinePreTrainedModel |
python | great-expectations__great_expectations | great_expectations/core/freshness_diagnostics.py | {
"start": 547,
"end": 1767
} | class ____:
"""
Wrapper around a list of errors; used to determine if a resource has been added successfully
and is "fresh" or up-to-date with its persisted equivalent.
Note that some resources may have dependencies on other resources - in order to be considered
"fresh", the root resource and all of its dependencies must be "fresh".
For example, a Checkpoint may have dependencies on ValidationDefinitions, which may have
dependencies on ExpectationSuites and BatchDefinitions.
GX requires that all resources are persisted successfully before they can be used to prevent
unexpected behavior.
"""
raise_for_error_class: ClassVar[Type[ResourceFreshnessAggregateError]] = (
ResourceFreshnessAggregateError
)
errors: list[GreatExpectationsError]
@property
def success(self) -> bool:
return len(self.errors) == 0
def raise_for_error(self) -> None:
"""
Conditionally raises an error if the resource has not been added successfully;
should prescribe the correct action(s) to take.
"""
if not self.success:
raise self.raise_for_error_class(errors=self.errors)
@dataclass
| FreshnessDiagnostics |
python | openai__openai-python | src/openai/types/responses/response_file_search_call_in_progress_event.py | {
"start": 214,
"end": 677
} | class ____(BaseModel):
item_id: str
"""The ID of the output item that the file search call is initiated."""
output_index: int
"""The index of the output item that the file search call is initiated."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["response.file_search_call.in_progress"]
"""The type of the event. Always `response.file_search_call.in_progress`."""
| ResponseFileSearchCallInProgressEvent |
python | joke2k__faker | faker/providers/misc/en_US/__init__.py | {
"start": 42,
"end": 81
} | class ____(MiscProvider):
pass
| Provider |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/service/distributed_save_ft_test.py | {
"start": 2875,
"end": 21422
} | class ____(data_service_test_base.TestBase, parameterized.TestCase):
maxDiff = None
@combinations.generate(test_base.default_test_combinations())
def testSnapshotRecoverySucceeds(self):
cluster = data_service_test_base.TestCluster(num_workers=1)
snapshot_dir = data_service_test_base.TempDir()
dataset = self._get_dataset()
self.evaluate(distributed_save_op.distributed_save(
dataset, snapshot_dir.full_path, cluster.dispatcher_address()))
cluster.restart_dispatcher()
@combinations.generate(test_base.default_test_combinations())
def testSnapshotRecoveryBlocksOverwrite(self):
cluster = data_service_test_base.TestCluster(num_workers=1)
snapshot_dir = data_service_test_base.TempDir()
dataset = self._get_dataset()
self.evaluate(distributed_save_op.distributed_save(
dataset, snapshot_dir.full_path, cluster.dispatcher_address()))
cluster.restart_dispatcher()
with self.assertRaisesRegex(
errors.AlreadyExistsError, "is already started or completed"):
self.evaluate(distributed_save_op.distributed_save(
dataset, snapshot_dir.full_path, cluster.dispatcher_address()))
# TODO(b/250921378): Figure out why tsan times out when there is a worker.
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
bad_stream_dir_name=["stream_", "stream_x", "stream_-1"])))
def testSnapshotRecoveryFailsWithBadStreamName(self, bad_stream_dir_name):
cluster = data_service_test_base.TestCluster(num_workers=0)
snapshot_dir = data_service_test_base.TempDir()
self.evaluate(distributed_save_op.distributed_save(
self._get_dataset(),
snapshot_dir.full_path,
cluster.dispatcher_address()))
self._make_stream_dir(snapshot_dir.full_path, bad_stream_dir_name)
with self.assertRaisesRegex(RuntimeError, "Can't parse"):
cluster.restart_dispatcher()
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
bad_source_dir_name=["source_", "source_x", "source_-1"])))
def testSnapshotRecoveryFailsWithBadSourceName(self, bad_source_dir_name):
cluster = data_service_test_base.TestCluster(num_workers=0)
snapshot_dir = data_service_test_base.TempDir()
self.evaluate(distributed_save_op.distributed_save(
self._get_dataset(),
snapshot_dir.full_path,
cluster.dispatcher_address()))
os.makedirs(os.path.join(self._splits_dir(snapshot_dir.full_path),
bad_source_dir_name))
with self.assertRaisesRegex(RuntimeError, "Can't parse"):
cluster.restart_dispatcher()
@combinations.generate(test_base.default_test_combinations())
def testSnapshotRecoveryFailsWithOutOfBoundsSourceName(self):
cluster = data_service_test_base.TestCluster(num_workers=0)
snapshot_dir = data_service_test_base.TempDir()
self.evaluate(distributed_save_op.distributed_save(
self._get_dataset(),
snapshot_dir.full_path,
cluster.dispatcher_address()))
os.makedirs(os.path.join(self._splits_dir(snapshot_dir.full_path),
"source_1"))
with self.assertRaisesRegex(RuntimeError, "Found conflict"):
cluster.restart_dispatcher()
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
bad_split_filename=[
"split_",
"split_x_0",
"split_-1_0",
"split_0_x",
"split_0_-1"])))
def testSnapshotRecoveryFailsWithBadSplitNames(self, bad_split_filename):
cluster = data_service_test_base.TestCluster(num_workers=0)
snapshot_dir = data_service_test_base.TempDir()
self.evaluate(distributed_save_op.distributed_save(
self._get_dataset(),
snapshot_dir.full_path,
cluster.dispatcher_address()))
write_file(os.path.join(self._source_dir(snapshot_dir.full_path),
bad_split_filename))
with self.assertRaisesRegex(
ValueError,
"Expected split_<local_split_index>_<global_split_index>"):
cluster.restart_dispatcher()
@combinations.generate(test_base.default_test_combinations())
def testSnapshotRecoveryFailsWithOutOfOrderSplitName(self):
cluster = data_service_test_base.TestCluster(num_workers=0)
snapshot_dir = data_service_test_base.TempDir()
self.evaluate(distributed_save_op.distributed_save(
self._get_dataset(),
snapshot_dir.full_path,
cluster.dispatcher_address()))
write_file(os.path.join(self._source_dir(snapshot_dir.full_path),
"split_1_0"))
with self.assertRaisesRegex(
ValueError,
"The local split index 1 exceeds the global split index 0"):
cluster.restart_dispatcher()
@combinations.generate(test_base.default_test_combinations())
def testSnapshotRecoveryFailsWithMissingGlobalIndexInSplitNames(self):
cluster = data_service_test_base.TestCluster(num_workers=0)
snapshot_dir = data_service_test_base.TempDir()
self.evaluate(distributed_save_op.distributed_save(
self._get_dataset(),
snapshot_dir.full_path,
cluster.dispatcher_address()))
write_file(os.path.join(self._source_dir(snapshot_dir.full_path),
"split_0_1"))
with self.assertRaisesRegex(RuntimeError, "Found missing global"):
cluster.restart_dispatcher()
@combinations.generate(test_base.default_test_combinations())
def testSnapshotRecoveryFailsWithDuplicateGlobalIndexInSplitName(self):
cluster = data_service_test_base.TestCluster(num_workers=0)
snapshot_dir = data_service_test_base.TempDir()
self.evaluate(distributed_save_op.distributed_save(
self._get_dataset(),
snapshot_dir.full_path,
cluster.dispatcher_address()))
write_file(os.path.join(self._source_dir(
snapshot_dir.full_path, stream_idx=0), "split_0_1"))
write_file(os.path.join(self._source_dir(
snapshot_dir.full_path, stream_idx=1, worker=1), "split_0_1"))
with self.assertRaisesRegex(RuntimeError, "Found duplicate global"):
cluster.restart_dispatcher()
@combinations.generate(test_base.default_test_combinations())
def testSnapshotRecoveryFailsWithDuplicateWorkerAssignment(self):
cluster = data_service_test_base.TestCluster(num_workers=0)
snapshot_dir = data_service_test_base.TempDir()
self.evaluate(distributed_save_op.distributed_save(
self._get_dataset(),
snapshot_dir.full_path,
cluster.dispatcher_address()))
write_file(os.path.join(
self._source_dir(snapshot_dir.full_path, stream_idx=0), "split_0_1"))
write_file(os.path.join(
self._source_dir(snapshot_dir.full_path, stream_idx=1), "split_0_1"))
with self.assertRaisesRegex(RuntimeError, "worker is already assigned"):
cluster.restart_dispatcher()
@combinations.generate(test_base.default_test_combinations())
def testStreamsReassignedAfterDispatcherRestart(self):
n = 5
cluster = data_service_test_base.TestCluster(num_workers=n)
snapshot_dir = data_service_test_base.TempDir()
dataset = self._get_dataset(dataset_range=10000)
self.evaluate(distributed_save_op.distributed_save(
dataset, snapshot_dir.full_path, cluster.dispatcher_address()))
get_streams = lambda: cluster.snapshot_streams(snapshot_dir.full_path)
while len(get_streams()) != n:
time.sleep(0.1)
cluster.restart_dispatcher()
streams = get_streams()
while len(streams) != n:
time.sleep(0.1)
streams = get_streams()
self.assertCountEqual([stream.index for stream in streams], range(n))
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
worker_max_concurrent_snapshots=[1, 2])))
def testWorkersDontExceedMaxStreamAssignments(
self, worker_max_concurrent_snapshots):
num_workers = 2
num_snapshots = 10
cluster = data_service_test_base.TestCluster(
num_workers=num_workers,
worker_max_concurrent_snapshots=worker_max_concurrent_snapshots)
snapshot_dir = data_service_test_base.TempDir()
paths = []
for i in range(num_snapshots):
paths.append(f"{snapshot_dir.full_path}_{i}")
self.evaluate(
distributed_save_op.distributed_save(
dataset_ops.Dataset.range(5000),
paths[i],
cluster.dispatcher_address()))
# A mapping of worker idx to max active assignments observed at any time.
max_assignments = collections.defaultdict(int)
def get_assignments_and_update_max_assignments():
assignments = get_stream_assignments(
cluster, num_workers, paths, block=False, active_only=True)
for worker_idx, worker_assignments in assignments.items():
max_assignments[worker_idx] = max(max_assignments[worker_idx],
len(worker_assignments))
return assignments
# Blocks until each worker has at least the max expected active assignments.
while True:
assignments = get_assignments_and_update_max_assignments()
all_workers_have_assignments = len(assignments) == num_workers
each_worker_has_enough_assignments = all([
len(per_worker_assignments) >= worker_max_concurrent_snapshots
for per_worker_assignments in assignments.values()])
if all_workers_have_assignments and each_worker_has_enough_assignments:
break
time.sleep(0.1)
cluster.restart_dispatcher()
wait_for_snapshot(paths, get_assignments_and_update_max_assignments)
self.assertValuesEqual(list(max_assignments.values()),
[worker_max_concurrent_snapshots] * num_workers)
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(num_workers=[1, 3])))
def testDatasetRecoversAndCompletes(self, num_workers):
cluster = data_service_test_base.TestCluster(num_workers=num_workers)
snapshot_dir = data_service_test_base.TempDir()
dataset = dataset_ops.Dataset.range(1000)
self.evaluate(
distributed_save_op.distributed_save(
dataset,
snapshot_dir.full_path,
cluster.dispatcher_address(),
compression=None))
for i in range(num_workers):
cluster.stop_worker(i)
cluster.restart_dispatcher()
cluster.restart_worker(i)
wait_for_snapshot(snapshot_dir.full_path)
self.assertTrue(snapshot_is_done(snapshot_dir.full_path))
dataset = dataset_ops.Dataset.load(snapshot_dir.full_path)
self.assertDatasetProduces(dataset, range(1000), assert_items_equal=True)
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(num_workers=[1, 3], num_sources=[1, 3])))
def testLargeMultiSourceSnapshotRecoversAndCompletes(
self, num_workers, num_sources):
cluster = data_service_test_base.TestCluster(num_workers=num_workers)
snapshot_dir = data_service_test_base.TempDir()
dataset = self._get_dataset(dataset_range=1000, num_sources=num_sources)
self.evaluate(distributed_save_op.distributed_save(
dataset, snapshot_dir.full_path, cluster.dispatcher_address()))
for i in range(num_workers):
cluster.stop_worker(i)
cluster.restart_dispatcher()
cluster.restart_worker(i)
wait_for_snapshot(snapshot_dir.full_path)
self.assertTrue(snapshot_is_done(snapshot_dir.full_path))
if num_workers > 1:
# Can't verify the elements with more than 1 worker since the splits
# receive by each worker for each source is non-deterministic.
# For example, with dynamic sharding, worker 1 may receive 999 splits for
# source 0 and 0 splis for source 1; worker 2 may receive 0 splits for
# source 0 and 999 splits for source 1. In this case, the snapshot will
# contain no elements since `zip` drops the elements when the zipped
# datasets have different cardinalities.
return
dataset = dataset_ops.Dataset.load(snapshot_dir.full_path)
expected = (
list(range(1000))
if num_sources == 1
else list(zip(*([range(1000)] * num_sources))))
self.assertDatasetProduces(dataset, expected, assert_items_equal=True)
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
num_elements=[1, 2, 1000],
num_workers=[1, 3],
num_repetitions=[1, 10])))
def testRepeatedDatasetRecoversAndCompletes(
self, num_elements, num_workers, num_repetitions):
cluster = data_service_test_base.TestCluster(num_workers=num_workers)
snapshot_dir = data_service_test_base.TempDir()
ds = dataset_ops.Dataset.range(num_elements)
ds = ds.repeat(num_repetitions)
self.evaluate(distributed_save_op.distributed_save(
ds, snapshot_dir.full_path, cluster.dispatcher_address()))
for i in range(num_workers):
cluster.stop_worker(i)
cluster.restart_dispatcher()
cluster.restart_worker(i)
wait_for_snapshot(snapshot_dir.full_path)
self.assertTrue(snapshot_is_done(snapshot_dir.full_path))
dataset = dataset_ops.Dataset.load(snapshot_dir.full_path)
self.assertDatasetProduces(
dataset,
list(range(num_elements)) * num_repetitions,
assert_items_equal=True)
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(num_workers=[1, 5], num_sources=[1, 3])))
def testNonrepeatedDatasetDoesntProduceSecondRepetitionDir(
self, num_workers, num_sources):
cluster = data_service_test_base.TestCluster(num_workers=num_workers)
snapshot_dir = data_service_test_base.TempDir()
dataset = self._get_dataset(dataset_range=1000, num_sources=num_sources)
self.evaluate(distributed_save_op.distributed_save(
dataset, snapshot_dir.full_path, cluster.dispatcher_address()))
for i in range(num_workers):
cluster.stop_worker(i)
cluster.restart_dispatcher()
cluster.restart_worker(i)
wait_for_snapshot(snapshot_dir.full_path)
self.assertTrue(snapshot_is_done(snapshot_dir.full_path))
for stream_idx in range(num_workers):
for source_idx in range(num_sources):
self.assertFalse(
os.path.exists(
os.path.join(
snapshot_dir.full_path,
"streams",
f"stream_{stream_idx}",
"splits",
f"source_{source_idx}",
"repetition_1")))
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(num_workers=[1, 3])))
def testMultipleDatasetRecoversAndCompletes(self, num_workers):
cluster = data_service_test_base.TestCluster(num_workers=num_workers)
snapshot_dir = data_service_test_base.TempDir()
dataset1 = dataset_ops.Dataset.range(1000)
datasets = [
dataset_ops.Dataset.from_tensors("a").repeat(50),
dataset_ops.Dataset.from_tensors("b").repeat(50),
dataset_ops.Dataset.from_tensors("c").repeat(50)]
choice_dataset = dataset_ops.Dataset.range(3).repeat()
dataset2 = dataset_ops.Dataset.choose_from_datasets(
datasets, choice_dataset)
snapshot_path1 = os.path.join(snapshot_dir.full_path, "snapshot1")
snapshot_path2 = os.path.join(snapshot_dir.full_path, "snapshot2")
self.evaluate(
distributed_save_op.distributed_save(
dataset1, snapshot_path1, cluster.dispatcher_address()))
self.evaluate(
distributed_save_op.distributed_save(
dataset2, snapshot_path2, cluster.dispatcher_address()))
for i in range(num_workers):
cluster.stop_worker(i)
cluster.restart_dispatcher()
cluster.restart_worker(i)
wait_for_snapshot(snapshot_path1)
wait_for_snapshot(snapshot_path2)
dataset = dataset_ops.Dataset.load(snapshot_path1)
self.assertDatasetProduces(
dataset, list(range(1000)), assert_items_equal=True)
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(num_workers=[1, 3])))
def testNestedDataset(self, num_workers):
cluster = data_service_test_base.TestCluster(num_workers=num_workers)
snapshot_dir = data_service_test_base.TempDir()
dataset = dataset_ops.Dataset.from_tensor_slices(range(100))
def interleave_fn(x):
ds = dataset_ops.Dataset.from_tensor_slices(range(x))
def flat_map_fn(y):
return dataset_ops.Dataset.from_tensor_slices([y])
return ds.flat_map(flat_map_fn)
dataset = dataset.interleave(
interleave_fn, cycle_length=2, num_parallel_calls=2)
self.evaluate(
distributed_save_op.distributed_save(
dataset, snapshot_dir.full_path, cluster.dispatcher_address()))
for i in range(num_workers):
cluster.stop_worker(i)
cluster.restart_dispatcher()
cluster.restart_worker(i)
wait_for_snapshot(snapshot_dir.full_path)
self.assertTrue(snapshot_is_done(snapshot_dir.full_path))
def _get_dataset(self, dataset_range=10, num_sources=1):
dataset = dataset_ops.Dataset.range(dataset_range)
if num_sources > 1:
dataset = dataset_ops.Dataset.zip((dataset,) * num_sources)
return dataset
def _splits_dir(self, snapshot_path, stream_idx=0, worker=0):
stream_name = f"stream_{stream_idx}"
self._make_stream_dir(snapshot_path, stream_name, worker=worker)
return os.path.join(snapshot_path, "streams", stream_name, "splits")
def _source_dir(self, snapshot_path, stream_idx=0, source_idx=0, worker=0):
return os.path.join(
self._splits_dir(snapshot_path, stream_idx, worker=worker),
f"source_{source_idx}",
"repetition_0")
def _make_stream_dir(self, snapshot_path, stream_name, worker=0):
stream_dir = os.path.join(snapshot_path, "streams", stream_name)
os.makedirs(stream_dir)
pathlib.Path(os.path.join(stream_dir, "owner_worker")).write_text(
f"{worker}")
if __name__ == "__main__":
test.main()
| SnapshotFtTest |
python | google__jax | jax/_src/pallas/core.py | {
"start": 48804,
"end": 50356
} | class ____(effects.Effect):
pass
comms_effect = CommsEffect()
effects.lowerable_effects.add_type(CommsEffect)
effects.control_flow_allowed_effects.add_type(CommsEffect)
effects.remat_allowed_effects.add_type(CommsEffect)
effects.custom_derivatives_allowed_effects.add_type(CommsEffect)
@core_map_p.def_effectful_abstract_eval
def _core_map_abstract_eval(*args, jaxpr, mesh, **kwargs):
del args
if jaxpr.outvars:
raise ValueError("core_map must not return any outputs.")
interpret = kwargs.get('interpret', False)
effs = set()
if interpret:
try:
from jax._src.pallas.mosaic.interpret import interpret_pallas_call as mosaic_tpu_interpret # Avoid circular dependency.
if isinstance(interpret, mosaic_tpu_interpret.InterpretParams):
effs = mosaic_tpu_interpret.get_interpret_effects()
except ImportError:
pass
for eff in jaxpr.effects:
if mesh.discharges_effect(eff) or isinstance(eff, CommsEffect):
continue
if not isinstance(eff, jax_core.NamedAxisEffect):
effs.add(eff)
continue
if eff.name not in mesh.shape:
effs.add(eff)
return [], effs
def core_map_lowering_rule(ctx: mlir.LoweringRuleContext,
*args,
jaxpr,
**kwargs
):
del ctx, args, kwargs
raise ValueError(
"Attempted to lower core_map without discharging. This can happen if "
"the core_map body does not modify any Refs or have other observable "
f"side-effects.\n Jaxpr of the body: {jaxpr}")
mlir.register_lowering(core_map_p, core_map_lowering_rule)
| CommsEffect |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_bundle_selections.py | {
"start": 1844,
"end": 3827
} | class ____(StreamTestCase):
_STREAM_NAME = "bundle_selections"
@HttpMocker()
def test_state_message_produced_while_read_and_state_match_latest_record(self, http_mocker: HttpMocker) -> None:
min_cursor_value = "2024-01-01T00:00:00+00:00"
max_cursor_value = "2024-02-01T00:00:00+00:00"
http_mocker.get(
self.stream_request().with_limit(250).with_updated_at_min(START_DATE).build(),
get_stream_response(_STREAM_NAME)
.with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD).with_cursor(min_cursor_value))
.with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD).with_cursor(max_cursor_value))
.build(),
)
output = read_incremental(self._config, _STREAM_NAME)
test_cursor_value = get_cursor_value_from_state_message(output, _CURSOR_FIELD)
assert test_cursor_value == max_cursor_value
@HttpMocker()
def test_given_multiple_pages_when_read_then_return_records_with_state(self, http_mocker: HttpMocker) -> None:
min_cursor_value = "2024-01-01T00:00:00+00:00"
max_cursor_value = "2024-02-01T00:00:00+00:00"
http_mocker.get(
self.stream_request().with_limit(250).with_next_page_token(NEXT_PAGE_TOKEN).build(),
get_stream_response(_STREAM_NAME).with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD)).build(),
)
http_mocker.get(
self.stream_request().with_limit(250).with_updated_at_min(START_DATE).build(),
get_stream_response(_STREAM_NAME)
.with_pagination()
.with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD).with_cursor(min_cursor_value))
.with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD).with_cursor(max_cursor_value))
.build(),
)
output = read_incremental(self._config, _STREAM_NAME)
assert len(output.records) == 3
| TestIncremental |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/properties.py | {
"start": 5096,
"end": 5540
} | class ____:
def foo(self):
pass
def bar(self):
pass
@property
def collided_property(self):
# Please ensure the target name of the inner function does not
# collide with the property setter of the outer function.
def setter(value):
self.foo()
setter(1)
@collided_property.setter
def collided_property(self, value):
self.bar()
| CollidePropertySetterName |
python | skorch-dev__skorch | skorch/tests/test_dataset.py | {
"start": 18923,
"end": 31560
} | class ____:
num_samples = 100
@staticmethod
def assert_datasets_equal(ds0, ds1):
"""Generic function to test equality of dataset values."""
assert len(ds0) == len(ds1)
# pylint: disable=consider-using-enumerate
for i in range(len(ds0)):
x0, y0 = ds0[i]
x1, y1 = ds1[i]
try:
assert x0 == x1
except (RuntimeError, ValueError):
assert (x0 == x1).all()
try:
assert y0 == y1
except (RuntimeError, ValueError):
assert (y0 == y1).all()
@pytest.fixture
def dataset_cls(self):
from skorch.dataset import Dataset
return Dataset
@pytest.fixture
def data(self, dataset_cls):
X = np.random.random((self.num_samples, 10))
assert self.num_samples % 4 == 0
y = np.repeat([0, 1, 2, 3], self.num_samples // 4)
return dataset_cls(X, y)
@pytest.fixture
def valid_split_cls(self):
from skorch.dataset import ValidSplit
return ValidSplit
def test_reproducible(self, valid_split_cls, data):
dataset_train0, dataset_valid0 = valid_split_cls(5)(data)
dataset_train1, dataset_valid1 = valid_split_cls(5)(data)
self.assert_datasets_equal(dataset_train0, dataset_train1)
self.assert_datasets_equal(dataset_valid0, dataset_valid1)
@pytest.mark.parametrize('cv', [2, 4, 5, 10])
def test_different_kfolds(self, valid_split_cls, cv, data):
if self.num_samples % cv != 0:
raise ValueError("Num samples not divisible by {}".format(cv))
dataset_train, dataset_valid = valid_split_cls(cv)(data)
assert len(dataset_train) + len(dataset_valid) == self.num_samples
assert len(dataset_valid) == self.num_samples // cv
@pytest.mark.parametrize('cv', [5, 0.2])
def test_stratified(self, valid_split_cls, data, cv):
num_expected = self.num_samples // 4
y = np.hstack([np.repeat([0, 0, 0], num_expected),
np.repeat([1], num_expected)])
data.y = y
dataset_train, dataset_valid = valid_split_cls(
cv, stratified=True)(data, y)
y_train = data_from_dataset(dataset_train)[1]
y_valid = data_from_dataset(dataset_valid)[1]
assert y_train.sum() == 0.8 * num_expected
assert y_valid.sum() == 0.2 * num_expected
@pytest.mark.parametrize('cv', [0.1, 0.2, 0.5, 0.75])
def test_different_fractions(self, valid_split_cls, cv, data):
if not (self.num_samples * cv).is_integer() != 0:
raise ValueError("Num samples cannot be evenly distributed for "
"fraction {}".format(cv))
dataset_train, dataset_valid = valid_split_cls(cv)(data)
assert len(dataset_train) + len(dataset_valid) == self.num_samples
assert len(dataset_valid) == self.num_samples * cv
@pytest.mark.parametrize('cv', [0.1, 0.2, 0.5, 0.75])
def test_fraction_no_y(self, valid_split_cls, data, cv):
if not (self.num_samples * cv).is_integer() != 0:
raise ValueError("Num samples cannot be evenly distributed for "
"fraction {}".format(cv))
m = int(cv * self.num_samples)
n = int((1 - cv) * self.num_samples)
dataset_train, dataset_valid = valid_split_cls(
cv, stratified=False)(data, None)
assert len(dataset_valid) == m
assert len(dataset_train) == n
def test_fraction_no_classifier(self, valid_split_cls, data):
y = np.random.random(self.num_samples)
data.y = y
cv = 0.2
m = int(cv * self.num_samples)
n = int((1 - cv) * self.num_samples)
dataset_train, dataset_valid = valid_split_cls(
cv, stratified=False)(data, y)
assert len(dataset_valid) == m
assert len(dataset_train) == n
@pytest.mark.parametrize('cv', [0, -0.001, -0.2, -3])
def test_bad_values_raise(self, valid_split_cls, cv):
with pytest.raises(ValueError) as exc:
valid_split_cls(cv)
expected = ("Numbers less than 0 are not allowed for cv "
"but ValidSplit got {}".format(cv))
assert exc.value.args[0] == expected
@pytest.mark.parametrize('cv', [5, 0.2])
def test_not_stratified(self, valid_split_cls, data, cv):
num_expected = self.num_samples // 4
y = np.hstack([np.repeat([0, 0, 0], num_expected),
np.repeat([1], num_expected)])
data.y = y
dataset_train, dataset_valid = valid_split_cls(
cv, stratified=False)(data, y)
y_train = data_from_dataset(dataset_train)[1]
y_valid = data_from_dataset(dataset_valid)[1]
# when not stratified, we cannot know the distribution of targets
assert y_train.sum() + y_valid.sum() == num_expected
def test_predefined_split(self, valid_split_cls, data):
from sklearn.model_selection import PredefinedSplit
indices = (data.y > 0).astype(int)
split = PredefinedSplit(indices)
dataset_train, dataset_valid = valid_split_cls(split)(data)
y_train = data_from_dataset(dataset_train)[1]
y_valid = data_from_dataset(dataset_valid)[1]
assert (y_train > 0).all()
assert (y_valid == 0).all()
def test_with_y_none(self, valid_split_cls, data):
data.y = None
m = self.num_samples // 5
n = self.num_samples - m
dataset_train, dataset_valid = valid_split_cls(5)(data)
assert len(dataset_train) == n
assert len(dataset_valid) == m
y_train = data_from_dataset(dataset_train)[1]
y_valid = data_from_dataset(dataset_valid)[1]
assert y_train is None
assert y_valid is None
def test_with_torch_tensors(self, valid_split_cls, data):
data.X = to_tensor(data.X, device='cpu')
data.y = to_tensor(data.y, device='cpu')
m = self.num_samples // 5
n = self.num_samples - m
dataset_train, dataset_valid = valid_split_cls(5)(data)
assert len(dataset_valid) == m
assert len(dataset_train) == n
def test_with_torch_tensors_and_stratified(self, valid_split_cls, data):
num_expected = self.num_samples // 4
data.X = to_tensor(data.X, device='cpu')
y = np.hstack([np.repeat([0, 0, 0], num_expected),
np.repeat([1], num_expected)])
data.y = to_tensor(y, device='cpu')
dataset_train, dataset_valid = valid_split_cls(5, stratified=True)(data, y)
y_train = data_from_dataset(dataset_train)[1]
y_valid = data_from_dataset(dataset_valid)[1]
assert y_train.sum() == 0.8 * num_expected
assert y_valid.sum() == 0.2 * num_expected
def test_with_list_of_arrays(self, valid_split_cls, data):
data.X = [data.X, data.X]
m = self.num_samples // 5
n = self.num_samples - m
dataset_train, dataset_valid = valid_split_cls(5)(data)
X_train, y_train = data_from_dataset(dataset_train)
X_valid, y_valid = data_from_dataset(dataset_valid)
assert len(X_train[0]) == len(X_train[1]) == len(y_train) == n
assert len(X_valid[0]) == len(X_valid[1]) == len(y_valid) == m
def test_with_dict(self, valid_split_cls, data):
data.X = {'1': data.X, '2': data.X}
dataset_train, dataset_valid = valid_split_cls(5)(data)
m = self.num_samples // 5
n = self.num_samples - m
X_train, y_train = data_from_dataset(dataset_train)
X_valid, y_valid = data_from_dataset(dataset_valid)
assert len(X_train['1']) == len(X_train['2']) == len(y_train) == n
assert len(X_valid['1']) == len(X_valid['2']) == len(y_valid) == m
@pytest.mark.skipif(not pandas_installed, reason='pandas is not installed')
def test_with_pandas(self, valid_split_cls, data):
import pandas as pd
data.X = pd.DataFrame(
data.X,
columns=[str(i) for i in range(data.X.shape[1])],
)
dataset_train, dataset_valid = valid_split_cls(5)(data)
m = self.num_samples // 5
X_train, y_train = data_from_dataset(dataset_train)
X_valid, y_valid = data_from_dataset(dataset_valid)
assert len(X_train) + len(X_valid) == self.num_samples
assert len(y_train) + len(y_valid) == self.num_samples
assert len(X_valid) == len(y_valid) == m
def test_y_str_val_stratified(self, valid_split_cls, data):
y = np.array(['a', 'a', 'a', 'b'] * (self.num_samples // 4))
if len(data.X) != len(y):
raise ValueError
data.y = y
dataset_train, dataset_valid = valid_split_cls(
5, stratified=True)(data, y)
y_train = data_from_dataset(dataset_train)[1]
y_valid = data_from_dataset(dataset_valid)[1]
assert np.isclose(np.mean(y_train == 'b'), 0.25)
assert np.isclose(np.mean(y_valid == 'b'), 0.25)
def test_y_list_of_arr_does_not_raise(self, valid_split_cls, data):
y = [np.zeros(self.num_samples), np.ones(self.num_samples)]
data.y = y
valid_split_cls(5, stratified=False)(data)
def test_y_list_of_arr_stratified(self, valid_split_cls, data):
y = [np.zeros(self.num_samples), np.ones(self.num_samples)]
data.y = y
with pytest.raises(ValueError) as exc:
valid_split_cls(5, stratified=True)(data, y)
expected = "Stratified CV requires explicitly passing a suitable y."
assert exc.value.args[0] == expected
def test_y_dict_does_not_raise(self, valid_split_cls, data):
y = {'a': np.zeros(self.num_samples), 'b': np.ones(self.num_samples)}
data.y = y
valid_split_cls(5, stratified=False)(data)
def test_y_dict_stratified_raises(self, valid_split_cls, data):
X = data[0]
y = {'a': np.zeros(len(X)), 'b': np.ones(len(X))}
with pytest.raises(ValueError):
# an sklearn error is raised
valid_split_cls(5, stratified=True)(X, y)
@pytest.mark.parametrize('cv', [5, 0.2])
@pytest.mark.parametrize('X', [np.zeros((100, 10)), torch.zeros((100, 10))])
def test_y_none_stratified(self, valid_split_cls, data, cv, X):
data.X = X
with pytest.raises(ValueError) as exc:
valid_split_cls(cv, stratified=True)(data, None)
expected = "Stratified CV requires explicitly passing a suitable y."
assert exc.value.args[0] == expected
def test_shuffle_split_reproducible_with_random_state(
self, valid_split_cls, dataset_cls):
n = self.num_samples
X, y = np.random.random((n, 10)), np.random.randint(0, 10, size=n)
cv = valid_split_cls(0.2, stratified=False)
dst0, dsv0 = cv(dataset_cls(X, y))
dst1, dsv1 = cv(dataset_cls(X, y))
Xt0, yt0 = data_from_dataset(dst0)
Xv0, yv0 = data_from_dataset(dsv0)
Xt1, yt1 = data_from_dataset(dst1)
Xv1, yv1 = data_from_dataset(dsv1)
assert not np.allclose(Xt0, Xt1)
assert not np.allclose(Xv0, Xv1)
assert not np.allclose(yt0, yt1)
assert not np.allclose(yv0, yv1)
def test_group_kfold(self, valid_split_cls, data):
from sklearn.model_selection import GroupKFold
X, y = data.X, data.y
n = self.num_samples // 2
groups = np.asarray(
[0 for _ in range(n)] + [1 for _ in range(self.num_samples - n)])
dataset_train, dataset_valid = valid_split_cls(
GroupKFold(n_splits=2))(data, groups=groups)
X_train, y_train = data_from_dataset(dataset_train)
X_valid, y_valid = data_from_dataset(dataset_valid)
assert np.allclose(X[:n], X_train)
assert np.allclose(y[:n], y_train)
assert np.allclose(X[n:], X_valid)
assert np.allclose(y[n:], y_valid)
def test_random_state_not_used_raises(self, valid_split_cls):
# Since there is no randomness involved, raise a ValueError when
# random_state is set, same as sklearn is now doing.
msg = (
r"Setting a random_state has no effect since cv is not a float. "
r"You should leave random_state to its default \(None\), or set cv "
r"to a float value."
)
with pytest.raises(ValueError, match=msg):
valid_split_cls(5, random_state=0)
def test_random_state_and_float_does_not_raise(self, valid_split_cls):
valid_split_cls(0.5, random_state=0) # does not raise
| TestValidSplit |
python | pytorch__pytorch | test/test_masked.py | {
"start": 8266,
"end": 11503
} | class ____(_TestParametrizer):
"""Decorator class for parametrization of test function with an input
layout argument and an extra argument of sample inputs generator.
The sample_inputs generator provides samples with all supported
layouts for the mask argument.
"""
def _parametrize_test(self, test, generic_cls, device_cls):
@wraps(test)
def wrap(self, layout, device, dtype, op):
layout_name = str(layout).lstrip('torch.')
if layout == torch.strided:
# strided layouts are always supported
sample_inputs_func = op.sample_inputs
elif layout == torch.sparse_coo:
if not op.supports_sparse:
raise unittest.SkipTest(f"{op.name} does not support inputs with {layout_name} layout")
sample_inputs_func = op.sample_inputs_sparse_coo
elif layout == torch.sparse_csr:
if not op.supports_sparse_csr:
raise unittest.SkipTest(f"{op.name} does not support inputs with {layout_name} layout")
sample_inputs_func = op.sample_inputs_sparse_csr
else:
raise NotImplementedError(f'{layout}')
def sample_inputs_generator():
for sample_input in sample_inputs_func(device, dtype):
mask = sample_input.kwargs.get('mask')
if mask is None:
yield sample_input
else:
if layout == sample_input.input.layout:
yield sample_input
if layout != torch.strided:
sample_input_kwargs = sample_input.kwargs.copy()
sample_input_kwargs.update(mask=mask.to_dense())
yield SampleInput(sample_input.input.clone(),
args=sample_input.args,
kwargs=sample_input_kwargs)
if layout != torch.sparse_coo and op.supports_sparse:
sample_input_kwargs = sample_input.kwargs.copy()
sample_input_kwargs.update(mask=mask.to_sparse())
yield SampleInput(sample_input.input.clone(),
args=sample_input.args,
kwargs=sample_input_kwargs)
if layout != torch.sparse_csr and op.supports_sparse_csr and sample_input.input.ndim == 2:
sample_input_kwargs = sample_input.kwargs.copy()
sample_input_kwargs.update(mask=mask.to_sparse_csr())
yield SampleInput(sample_input.input.clone(),
args=sample_input.args,
kwargs=sample_input_kwargs)
test(self, layout, device, dtype, op, sample_inputs_generator())
for layout in (torch.strided, torch.sparse_coo, torch.sparse_csr):
yield (wrap, str(layout).lstrip('torch.'), {'layout': layout}, lambda _: [])
| mask_layouts |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_P.py | {
"start": 9011,
"end": 10383
} | class ____(Benchmark):
r"""
PermFunction 1 objective function.
This class defines the PermFunction1 [1]_ global optimization problem. This is
a multimodal minimization problem defined as follows:
.. math::
f_{\text{PermFunction01}}(x) = \sum_{k=1}^n \left\{ \sum_{j=1}^n (j^k
+ \beta) \left[ \left(\frac{x_j}{j}\right)^k - 1 \right] \right\}^2
Here, :math:`n` represents the number of dimensions and
:math:`x_i \in [-n, n + 1]` for :math:`i = 1, ..., n`.
*Global optimum*: :math:`f(x) = 0` for :math:`x_i = i` for
:math:`i = 1, ..., n`
.. [1] Mishra, S. Global Optimization by Differential Evolution and
Particle Swarm Methods: Evaluation on Some Benchmark Functions.
Munich Personal RePEc Archive, 2006, 1005
TODO: line 560
"""
change_dimensionality = True
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-self.N] * self.N,
[self.N + 1] * self.N))
self.global_optimum = [list(range(1, self.N + 1))]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
b = 0.5
k = atleast_2d(arange(self.N) + 1).T
j = atleast_2d(arange(self.N) + 1)
s = (j ** k + b) * ((x / j) ** k - 1)
return sum(sum(s, axis=1) ** 2)
| PermFunction01 |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 114587,
"end": 115295
} | class ____(nn.Module):
def __init__(
self,
width: int,
layers: int,
heads: int,
attn_mask: Optional[torch.Tensor] = None,
use_checkpoint=False,
layer_norm_eps=1e-05,
):
super().__init__()
self.width = width
self.num_layers = layers
self.layers = nn.Sequential(
*[OneFormerTextTransformerLayer(width, heads, attn_mask, layer_norm_eps) for _ in range(layers)]
)
self.use_checkpoint = use_checkpoint
def forward(self, hidden_states: torch.Tensor):
for layer in self.layers:
hidden_states = layer(hidden_states)
return hidden_states
| OneFormerTextTransformer |
python | kubernetes-client__python | kubernetes/client/models/v1_success_policy.py | {
"start": 383,
"end": 4501
} | 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 = {
'rules': 'list[V1SuccessPolicyRule]'
}
attribute_map = {
'rules': 'rules'
}
def __init__(self, rules=None, local_vars_configuration=None): # noqa: E501
"""V1SuccessPolicy - 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._rules = None
self.discriminator = None
self.rules = rules
@property
def rules(self):
"""Gets the rules of this V1SuccessPolicy. # noqa: E501
rules represents the list of alternative rules for the declaring the Jobs as successful before `.status.succeeded >= .spec.completions`. Once any of the rules are met, the \"SuccessCriteriaMet\" condition is added, and the lingering pods are removed. The terminal state for such a Job has the \"Complete\" condition. Additionally, these rules are evaluated in order; Once the Job meets one of the rules, other rules are ignored. At most 20 elements are allowed. # noqa: E501
:return: The rules of this V1SuccessPolicy. # noqa: E501
:rtype: list[V1SuccessPolicyRule]
"""
return self._rules
@rules.setter
def rules(self, rules):
"""Sets the rules of this V1SuccessPolicy.
rules represents the list of alternative rules for the declaring the Jobs as successful before `.status.succeeded >= .spec.completions`. Once any of the rules are met, the \"SuccessCriteriaMet\" condition is added, and the lingering pods are removed. The terminal state for such a Job has the \"Complete\" condition. Additionally, these rules are evaluated in order; Once the Job meets one of the rules, other rules are ignored. At most 20 elements are allowed. # noqa: E501
:param rules: The rules of this V1SuccessPolicy. # noqa: E501
:type: list[V1SuccessPolicyRule]
"""
if self.local_vars_configuration.client_side_validation and rules is None: # noqa: E501
raise ValueError("Invalid value for `rules`, must not be `None`") # noqa: E501
self._rules = rules
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, V1SuccessPolicy):
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, V1SuccessPolicy):
return True
return self.to_dict() != other.to_dict()
| V1SuccessPolicy |
python | kamyu104__LeetCode-Solutions | Python/find-the-safest-path-in-a-grid.py | {
"start": 765,
"end": 2662
} | class ____(object):
def maximumSafenessFactor(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def bfs():
dist = [[0 if grid[r][c] == 1 else -1 for c in xrange(len(grid[0]))] for r in xrange(len(grid))]
q = [(r, c) for r in xrange(len(grid)) for c in xrange(len(grid[0])) if grid[r][c]]
d = 0
while q:
new_q = []
for r, c in q:
for dr, dc in DIRECTIONS:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(dist) and 0 <= nc < len(dist[0]) and dist[nr][nc] == -1):
continue
dist[nr][nc] = d+1
new_q.append((nr, nc))
q = new_q
d += 1
return dist
dist = bfs()
buckets = [[] for _ in xrange((len(grid)-1)+(len(grid[0])-1)+1)]
for r in xrange(len(grid)):
for c in xrange(len(grid[0])):
buckets[dist[r][c]].append((r, c))
lookup = [[False]*len(grid[0]) for _ in xrange(len(grid))]
uf = UnionFind(len(grid)*len(grid[0]))
for d in reversed(xrange(len(buckets))):
for r, c in buckets[d]:
for dr, dc in DIRECTIONS:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(dist) and 0 <= nc < len(dist[0]) and lookup[nr][nc] == True):
continue
uf.union_set(nr*len(grid[0])+nc, r*len(grid[0])+c)
lookup[r][c] = True
if uf.find_set(0*len(grid[0])+0) == uf.find_set((len(grid)-1)*len(grid[0])+(len(grid[0])-1)):
break
return d
# Time: O(n^2 * logn)
# Space: O(n^2)
import heapq
# bfs, dijkstra's algorithm
| Solution |
python | pyinstaller__pyinstaller | PyInstaller/lib/modulegraph/modulegraph.py | {
"start": 25318,
"end": 26357
} | class ____(Package):
"""
Graph node representing a non-namespace Python package dynamically defined
at runtime.
Most packages are statically defined on-disk as standard subdirectories
containing `__init__.py` files. Some packages, however, are dynamically
defined in-memory at runtime (e.g., `six.moves`, dynamically defined by
the statically defined `six` module).
This node represents such a runtime package. All attributes imported from
this package in `from`-style import statements that are submodules of this
package (e.g., the `queue` submodule in `from six.moves import queue`) will
be imported rather than ignored.
To ensure that the parent package of this package if any is also imported
and added to the graph, this node is typically added to the graph by
calling the `ModuleGraph.add_module()` method.
"""
pass
#FIXME: Safely removable. We don't actually use this anywhere. After removing
#this class, remove the corresponding entry from "compat".
| RuntimePackage |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 26533,
"end": 26635
} | class ____(BaseModel, extra="forbid"):
datetime: str = Field(..., description="")
| DatetimeExpression |
python | google__jax | tests/pjit_test.py | {
"start": 338364,
"end": 349028
} | class ____(jtu.JaxTestCase):
@check_1d_2d_mesh(set_mesh=True)
def testNonDivisibleArgs(self, mesh, resources):
x = jnp.ones((3, 2))
spec = P(resources, None)
mesh_size = str(math.prod([dim[1] for dim in mesh]))
error = re.compile(
r"One of pjit arguments with pytree key path x.*" + spec_regex(spec) + r".*"
r"implies that the global size of its dimension 0 should be "
r"divisible by " + mesh_size + r", but it is equal to 3 "
r"\(full shape: \(3, 2\)\)", re.M | re.S)
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x, in_shardings=spec, out_shardings=None)(x)
@check_1d_2d_mesh(set_mesh=True)
def testNonDivisibleOuts(self, mesh, resources):
x = jnp.ones((3, 2))
spec = P(resources, None)
mesh_size = str(math.prod([dim[1] for dim in mesh]))
error = re.compile(
r"One of pjit outputs with pytree key path result\['rrr'\].*" + spec_regex(spec) + r".*"
r"implies that the global size of its dimension 0 should be "
r"divisible by " + mesh_size + r", but it is equal to 3", re.M | re.S)
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: {'rrr': x}, in_shardings=None,
out_shardings=P(resources, None))(x)
@check_1d_2d_mesh(set_mesh=False)
@jtu.with_mesh([('z', 1)])
def testUndefinedResourcesArgs(self, mesh, resources):
x = jnp.ones((2, 2))
spec = P(resources,)
with self.assertRaisesRegex(
ValueError,
r"Resource axis: x of.*" + spec_regex(spec) + r" is not found in mesh: \(.*\)."):
pjit(lambda x: x, in_shardings=spec, out_shardings=None)(x)
@check_1d_2d_mesh(set_mesh=False)
@jtu.with_mesh([('z', 1)])
def testUndefinedResourcesOuts(self, mesh, resources):
x = jnp.ones((2, 2))
spec = P(resources,)
with self.assertRaisesRegex(
ValueError,
r"Resource axis: x of.*" + spec_regex(spec) + r" is not found in mesh: \(.*\)."):
pjit(lambda x: x, in_shardings=None, out_shardings=spec)(x)
@check_1d_2d_mesh(set_mesh=False)
@jtu.with_mesh([('z', 1)])
def testUndefinedResourcesConstraint(self, mesh, resources):
x = jnp.ones((2, 2))
spec = P(resources,)
with self.assertRaisesRegex(
ValueError,
r"Resource axis: x of.*" + spec_regex(spec) + r" is not found in mesh: \(.*\)."):
pjit(
lambda x: with_sharding_constraint(x, spec),
in_shardings=None,
out_shardings=None,
)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRankTooLowArgs(self):
x = jnp.arange(2)
spec = P('x', 'y')
error = re.compile(
r"One of pjit arguments.*" + spec_regex(spec) +
r".*rank at least 2, but was applied to a value of rank 1", re.M | re.S)
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x.sum(), in_shardings=spec, out_shardings=None)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRankTooLowArgsAxisResourcesNone(self):
x = jnp.arange(2)
spec = P(None, None)
error = re.compile(
r"One of pjit arguments.*" + spec_regex(spec) +
r".*rank at least 2, but was applied to a value of rank 1", re.M | re.S)
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x.sum(), in_shardings=spec, out_shardings=None)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRankTooLowOuts(self):
x = jnp.arange(2)
spec = P('x', 'y')
error = re.compile(
r"One of pjit outputs.*" + spec_regex(spec) +
r".*rank at least 2, but was applied to a value of rank 0", re.M | re.S)
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x.sum(), in_shardings=None, out_shardings=spec)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRankTooLowConstraint(self):
x = jnp.arange(2)
spec = P('x', 'y')
error = re.compile(
r"One of with_sharding_constraint arguments" + r".*" + spec_regex(spec) +
r".*rank at least 2, but was applied to a value of rank 1", re.M | re.S)
with self.assertRaisesRegex(ValueError, error):
pjit(
lambda x: with_sharding_constraint(x, spec), in_shardings=None,
out_shardings=None,
)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRepeatedInResources(self):
x = jnp.arange(2)
for spec in [P('x', 'x'), P('x', ('y', 'x'))]:
error = (r"A single in_shardings specification can map every mesh "
r"axis to at most one positional dimension, but " +
spec_regex(spec) + " has duplicate entries for `x`")
with self.assertRaisesRegex(DuplicateSpecError, error):
pjit(lambda x: x, in_shardings=spec, out_shardings=None)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRepeatedOutResources(self):
x = jnp.arange(2)
for spec in [P('x', 'x'), P('x', ('y', 'x'))]:
error = (r"A single out_shardings specification can map every mesh "
r"axis to at most one positional dimension, but " +
spec_regex(spec) + " has duplicate entries for `x`")
with self.assertRaisesRegex(DuplicateSpecError, error):
pjit(lambda x: x, in_shardings=None, out_shardings=spec)(x)
def testEmptyMesh(self):
out = pjit(lambda x: x, in_shardings=None, out_shardings=None)(jnp.arange(4))
self.assertEqual(out.sharding, SingleDeviceSharding(jax.devices()[0]))
def test_pspec_to_wsc_without_mesh(self):
error = r'with_sharding_constraint requires a non-empty mesh in context.*'
with self.assertRaisesRegex(RuntimeError, error):
pjit(lambda x: with_sharding_constraint(x, P('x')))(jnp.arange(4))
@jtu.with_mesh([('x', 2)])
def testAxisResourcesMismatch(self):
x = jnp.ones([])
p = [None, None, None]
pjit(lambda x: x, (p,), p)([x, x, x]) # OK
error = re.escape(
"pjit in_shardings specification must be a tree prefix of the "
"positional arguments tuple. "
"In particular, pjit in_shardings must either be a Sharding, a "
"PartitionSpec, or a tuple of length equal to the number of positional "
"arguments. But pjit in_shardings is the wrong length: got a "
"tuple or list of length 3 for an args tuple of length 2.")
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x, y: x, p, p)(x, x)
Foo = namedtuple('Foo', ['x'])
error = "in_shardings is not a tuple.*might need to be wrapped"
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x, Foo(None), Foo(None))(Foo(x))
pjit(lambda x: x, (Foo(None),), Foo(None))(Foo(x)) # OK w/ singleton tuple
# TODO(apaszke,mattjj): Disable implicit list casts and enable this
# error = ("it looks like pjit in_axis_resources might need to be wrapped in "
# "a singleton tuple.")
# with self.assertRaisesRegex(ValueError, error):
# pjit(lambda x, y: x, p, p)([x, x, x])
# TODO(apaszke): Disable implicit list casts and enable this
# error = re.escape(
# r"pjit in_axis_resources specification must be a tree prefix of the "
# r"corresponding value, got specification (None, None, None) for value "
# r"tree PyTreeDef(([*, *, *],)). Note that pjit in_axis_resources that "
# r"are non-trivial pytrees should always be wrapped in a tuple representing "
# r"the argument list. In particular, you're passing in a single argument "
# r"which means that pjit in_axis_resources might need to be wrapped in a "
# r"singleton tuple.")
# with self.assertRaisesRegex(ValueError, error):
# pjit(lambda x: x, p, p)([x, x, x]) # Error, but make sure we hint at singleton tuple
error = re.escape(
"pytree structure error: different lengths of list at "
"key path\n"
" pjit out_shardings\n")
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x, (p,), [p, None])([x, x, x]) # Error, we raise a generic tree mismatch message
@jtu.with_mesh([('x', 2)])
def testNestedDifferentResources(self):
@partial(pjit, in_shardings=P('x'), out_shardings=None)
def f(x):
with jax.sharding.Mesh(np.array([jax.local_devices()[0]]), ('x')):
@partial(pjit, in_shardings=P('x'), out_shardings=None)
def h(x):
return x
return h(x)
xshape = (2, 5, 6)
x = jnp.arange(math.prod(xshape)).reshape(xshape)
with self.assertRaisesRegex(
ValueError, ".*cannot change the size of the mesh.*"):
f(x)
@parameterized.named_parameters(
("committed", True),
("uncommitted", False),
)
def test_pjit_with_deleted_input_at_first_call(self, committed):
shape = (8,)
mesh = jtu.create_mesh((1,), ('x',))
inp_data = np.arange(math.prod(shape)).reshape(shape)
if committed:
s = NamedSharding(mesh, P('x',))
x = jax.device_put(inp_data, s)
else:
x = jax.device_put(inp_data)
f = pjit(lambda x: x + 1)
with self.assertRaisesRegex(RuntimeError, 'Array has been deleted.'):
x.delete()
_ = f(x)
@parameterized.named_parameters(
("committed", True),
("uncommitted", False),
)
def test_pjit_with_deleted_input_at_subsequent_call(self, committed):
shape = (8,)
mesh = jtu.create_mesh((1,), ('x',))
inp_data = np.arange(math.prod(shape)).reshape(shape)
if committed:
s = NamedSharding(mesh, P('x',))
x = jax.device_put(inp_data, s)
else:
x = jax.device_put(inp_data)
f = pjit(lambda x: x + 1)
_ = f(x)
with self.assertRaisesRegex((RuntimeError, ValueError),
'.*(Array|buffer|Buffer) has been deleted.*'):
x.delete()
_ = f(x)
def test_aot_error_on_dced_avals_mismatch(self):
x, y1, y2 = jnp.ones(4), jnp.ones(4), jnp.ones(1)
@jax.jit
def f(x, y):
return x + 1 if y.shape[0] > 2 else x + 2
f_out1 = f(x, y1)
f(x, y2)
g = f.lower(x, y1).compile()
g_out1 = g(x, y1)
self.assertArraysEqual(f_out1, g_out1)
with self.assertRaisesRegex(
TypeError,
'Argument types differ from the types for which this computation was'
' compiled'):
g(x, y2)
def test_dce_no_array(self):
mesh = jtu.create_mesh((2,), ('x',))
arr = jax.device_put(np.arange(8.), NamedSharding(mesh, P('x')))
@jax.jit
def f(a, b, c):
return a, c
f(arr, 2., 3.)
f(arr, 2., 3.) # doesn't crash
def test_named_sharding_of_none(self):
mesh = jtu.create_mesh((2,), ('x',))
with self.assertRaisesRegex(
TypeError, '(Unexpected None|incompatible function arguments)'):
jax.NamedSharding(mesh, None)
@jtu.pytest_mark_if_available('multiaccelerator')
| PJitErrorTest |
python | numpy__numpy | numpy/lib/tests/test_shape_base.py | {
"start": 10421,
"end": 11854
} | class ____:
def test_functionality(self):
s = (2, 3, 4, 5)
a = np.empty(s)
for axis in range(-5, 4):
b = expand_dims(a, axis)
assert_(b.shape[axis] == 1)
assert_(np.squeeze(b).shape == s)
def test_axis_tuple(self):
a = np.empty((3, 3, 3))
assert np.expand_dims(a, axis=(0, 1, 2)).shape == (1, 1, 1, 3, 3, 3)
assert np.expand_dims(a, axis=(0, -1, -2)).shape == (1, 3, 3, 3, 1, 1)
assert np.expand_dims(a, axis=(0, 3, 5)).shape == (1, 3, 3, 1, 3, 1)
assert np.expand_dims(a, axis=(0, -3, -5)).shape == (1, 1, 3, 1, 3, 3)
def test_axis_out_of_range(self):
s = (2, 3, 4, 5)
a = np.empty(s)
assert_raises(AxisError, expand_dims, a, -6)
assert_raises(AxisError, expand_dims, a, 5)
a = np.empty((3, 3, 3))
assert_raises(AxisError, expand_dims, a, (0, -6))
assert_raises(AxisError, expand_dims, a, (0, 5))
def test_repeated_axis(self):
a = np.empty((3, 3, 3))
assert_raises(ValueError, expand_dims, a, axis=(1, 1))
def test_subclasses(self):
a = np.arange(10).reshape((2, 5))
a = np.ma.array(a, mask=a % 3 == 0)
expanded = np.expand_dims(a, axis=1)
assert_(isinstance(expanded, np.ma.MaskedArray))
assert_equal(expanded.shape, (2, 1, 5))
assert_equal(expanded.mask.shape, (2, 1, 5))
| TestExpandDims |
python | streamlit__streamlit | e2e_playwright/conftest.py | {
"start": 2798,
"end": 10153
} | class ____:
"""A context manager. Wraps subprocess. Popen to capture output safely."""
args: list[str]
cwd: str
env: dict[str, str]
_proc: subprocess.Popen[str] | None
_stdout_file: TextIOWrapper | None
def __init__(self, args: list[str], cwd: str, env: dict[str, str] | None = None):
self.args = args
self.cwd = cwd
self.env = env or {}
self._proc = None
self._stdout_file = None
def terminate(self) -> str | None:
"""Terminate the process and return its stdout/stderr in a string."""
if self._proc is not None:
self._proc.terminate()
self._proc.wait()
self._proc = None
# Read the stdout file and close it
stdout = None
if self._stdout_file is not None:
self._stdout_file.seek(0)
stdout = self._stdout_file.read()
self._stdout_file.close()
self._stdout_file = None
return stdout
def __enter__(self) -> Self:
self.start()
return self
def start(self) -> None:
# Start the process and capture its stdout/stderr output to a temp
# file. We do this instead of using subprocess.PIPE (which causes the
# Popen object to capture the output to its own internal buffer),
# because large amounts of output can cause it to deadlock.
self._stdout_file = TemporaryFile("w+")
print(f"Running: {shlex.join(self.args)}")
self._proc = subprocess.Popen(
self.args,
cwd=self.cwd,
stdout=self._stdout_file,
stderr=subprocess.STDOUT,
text=True,
env={**os.environ.copy(), **self.env},
)
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
if self._proc is not None:
self._proc.terminate()
self._proc = None
if self._stdout_file is not None:
self._stdout_file.close()
self._stdout_file = None
def resolve_test_to_script(test_module: ModuleType) -> str:
"""Resolve the test module to the corresponding test script filename."""
assert test_module.__file__ is not None
return test_module.__file__.replace("_test.py", ".py")
def hash_to_range(
text: str,
min: int = 10000,
max: int = 65535,
) -> int:
sha256_hash = hashlib.sha256(text.encode("utf-8")).hexdigest()
return min + (int(sha256_hash, 16) % (max - min + 1))
def is_port_available(port: int, host: str) -> bool:
"""Check if a port is available on the given host."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
return sock.connect_ex((host, port)) != 0
def find_available_port(
min_port: int = 10000,
max_port: int = 65535,
max_tries: int = 50,
host: str = "localhost",
) -> int:
"""Find an available port on the given host."""
for _ in range(max_tries):
selected_port = randint(min_port, max_port)
if is_port_available(selected_port, host):
return selected_port
raise RuntimeError("Unable to find an available port.")
def is_app_server_running(port: int, host: str = "localhost") -> bool:
"""Check if the app server is running."""
try:
return (
requests.get(f"http://{host}:{port}/_stcore/health", timeout=1).text == "ok"
)
except Exception:
return False
def wait_for_app_server_to_start(port: int, timeout: int = 5) -> bool:
"""Wait for the app server to start.
Parameters
----------
port : int
The port on which the app server is running.
timeout : int
The number of minutes to wait for the app server to start.
Returns
-------
bool
True if the app server is started, False otherwise.
"""
print(f"Waiting for app to start... {port}")
start_time = time.time()
while not is_app_server_running(port):
time.sleep(3)
if time.time() - start_time > 60 * timeout:
return False
return True
# region Fixtures
@pytest.fixture(scope="module")
def app_port(worker_id: str) -> int:
"""Fixture that returns an available port on localhost."""
if worker_id and worker_id != "master":
# This is run with xdist, we try to get a port by hashing the worker ID
port = hash_to_range(worker_id)
if is_port_available(port, "localhost"):
return port
# Find a random available port:
return find_available_port()
@pytest.fixture(scope="module")
def app_server_extra_args() -> list[str]:
"""Fixture that returns extra arguments to pass to the Streamlit app server."""
return []
@pytest.fixture(scope="module", autouse=True)
def app_server(
app_port: int,
app_server_extra_args: list[str],
request: pytest.FixtureRequest,
) -> Generator[AsyncSubprocess, None, None]:
"""Fixture that starts and stops the Streamlit app server."""
streamlit_proc = start_app_server(
app_port,
request.module,
extra_args=app_server_extra_args,
)
yield streamlit_proc
streamlit_stdout = streamlit_proc.terminate()
print(streamlit_stdout, flush=True)
@pytest.fixture
def app(page: Page, app_port: int, request: pytest.FixtureRequest) -> Page:
"""Fixture that opens the app."""
marker = request.node.get_closest_marker("app_hash")
hash_fragment = ""
if marker:
hash_fragment = f"#{marker.args[0]}"
response: Response | None = None
try:
response = page.goto(f"http://localhost:{app_port}/{hash_fragment}")
except Exception as e:
print(e, flush=True)
if response is None:
raise RuntimeError("Unable to load page")
if response.status != 200:
print(f"Unsuccessful in loading page. Status: {response.status}", flush=True)
if response.status == 404:
print(
"404 error: try building the frontend with make frontend-fast",
flush=True,
)
raise RuntimeError("Unable to load page")
print("Successfully loaded page", flush=True)
start_capture_traces(page)
wait_for_app_loaded(page)
return page
@pytest.fixture
def static_app(
page: Page,
app_port: int,
request: pytest.FixtureRequest,
) -> Page:
"""Fixture that opens the app."""
query_param = request.node.get_closest_marker("query_param")
query_string = query_param.args[0] if query_param else ""
# Indicate this is a StaticPage
page.__class__ = StaticPage
page.goto(f"http://localhost:{app_port}/{query_string}")
start_capture_traces(page)
wait_for_app_loaded(page)
return page
@pytest.fixture
def app_with_query_params(
page: Page, app_port: int, request: pytest.FixtureRequest
) -> tuple[Page, dict[str, Any]]:
"""Fixture that opens the app with additional query parameters.
The query parameters are passed as a dictionary in the 'param' key of the request.
"""
query_params = request.param
query_string = parse.urlencode(query_params, doseq=True)
url = f"http://localhost:{app_port}/?{query_string}"
page.goto(url)
wait_for_app_loaded(page)
return page, query_params
@dataclass
| AsyncSubprocess |
python | pyodide__pyodide | src/py/pyodide/http/_exceptions.py | {
"start": 1335,
"end": 1477
} | class ____(OSError):
def __init__(self, reason: JsException) -> None:
super().__init__(reason.message)
# pyxhr exceptions
| AbortError |
python | PrefectHQ__prefect | src/prefect/input/run_input.py | {
"start": 1590,
"end": 3638
} | class ____(RunInput):
number: int
@flow
async def receiver_flow():
async for data in NumberData.receive():
squared = data.number ** 2
data.respond(NumberData(number=squared))
```
"""
from __future__ import annotations
import inspect
from inspect import isclass
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Coroutine,
Dict,
Generic,
Literal,
Optional,
Set,
Type,
TypeVar,
Union,
cast,
overload,
)
from uuid import UUID, uuid4
import anyio
import pydantic
from pydantic import ConfigDict
from typing_extensions import Self
from prefect.input.actions import (
create_flow_run_input,
create_flow_run_input_from_model,
ensure_flow_run_id,
filter_flow_run_input,
read_flow_run_input,
)
from prefect.utilities.asyncutils import sync_compatible
if TYPE_CHECKING:
from prefect.client.schemas.objects import FlowRunInput
from prefect.states import State
from prefect._internal.pydantic.v2_schema import create_v2_schema, is_v2_model
R = TypeVar("R", bound="RunInput")
T = TypeVar("T", bound="object")
Keyset = Dict[
Union[Literal["description"], Literal["response"], Literal["schema"]], str
]
def keyset_from_paused_state(state: "State") -> Keyset:
"""
Get the keyset for the given Paused state.
Args:
- state (State): the state to get the keyset for
"""
if not state.is_paused():
raise RuntimeError(f"{state.type.value!r} is unsupported.")
state_name = state.name or ""
base_key = f"{state_name.lower()}-{str(state.state_details.pause_key)}"
return keyset_from_base_key(base_key)
def keyset_from_base_key(base_key: str) -> Keyset:
"""
Get the keyset for the given base key.
Args:
- base_key (str): the base key to get the keyset for
Returns:
- Dict[str, str]: the keyset
"""
return {
"description": f"{base_key}-description",
"response": f"{base_key}-response",
"schema": f"{base_key}-schema",
}
| NumberData |
python | huggingface__transformers | tests/models/ministral/test_modeling_ministral.py | {
"start": 2240,
"end": 9784
} | class ____(unittest.TestCase):
def tearDown(self):
cleanup(torch_device, gc_collect=True)
@slow
def test_model_8b_logits(self):
input_ids = [1, 306, 4658, 278, 6593, 310, 2834, 338]
model = AutoModelForCausalLM.from_pretrained("mistralai/Ministral-8B-Instruct-2410", device_map="auto")
assert isinstance(model, MinistralForCausalLM)
input_ids = torch.tensor([input_ids]).to(model.model.embed_tokens.weight.device)
with torch.no_grad():
out = model(input_ids).logits.float().cpu()
# Expected mean on dim = -1
EXPECTED_MEAN = torch.tensor([[-1.5029, -7.2815, 4.5190, 0.5930, -5.2526, 3.0765, -0.6314, 1.8068]])
torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2)
# slicing logits[0, 0, 0:30]
EXPECTED_SLICE = torch.tensor([-3.9446, -3.9466, 0.6383, -3.9466, -3.9468, -3.9448, -3.9462, -3.9455,
-3.9451, -0.8244, -3.9472, -3.9458, -3.9460, -3.9406, -3.9462, -3.9462,
-3.9458, -3.9462, -3.9463, -3.9461, -3.9448, -3.9451, -3.9462, -3.9458,
-3.9455, -3.9452, -3.9458, -3.9469, -3.9460, -3.9464]) # fmt: skip
torch.testing.assert_close(out[0, 0, :30], EXPECTED_SLICE, rtol=1e-4, atol=1e-4)
del model
backend_empty_cache(torch_device)
gc.collect()
@slow
def test_model_8b_generation(self):
EXPECTED_TEXT_COMPLETION = "My favourite condiment is 100% natural, 100% organic, 100% free of"
prompt = "My favourite condiment is "
tokenizer = AutoTokenizer.from_pretrained("Mistralai/Ministral-8B-Instruct-2410")
model = MinistralForCausalLM.from_pretrained("Mistralai/Ministral-8B-Instruct-2410", device_map="auto")
input_ids = tokenizer.encode(prompt, return_tensors="pt").to(model.model.embed_tokens.weight.device)
# greedy generation outputs
generated_ids = model.generate(input_ids, max_new_tokens=20, temperature=0)
text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
self.assertEqual(EXPECTED_TEXT_COMPLETION, text)
del model
backend_empty_cache(torch_device)
gc.collect()
@require_bitsandbytes
@slow
@require_flash_attn
@pytest.mark.flash_attn_test
def test_model_8b_long_prompt(self):
EXPECTED_OUTPUT_TOKEN_IDS = [36850, 4112]
# An input with 4097 tokens that is above the size of the sliding window
input_ids = [1] + [306, 338] * 2048
model = MinistralForCausalLM.from_pretrained(
"Mistralai/Ministral-8B-Instruct-2410",
device_map="auto",
dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
)
input_ids = torch.tensor([input_ids]).to(model.model.embed_tokens.weight.device)
generated_ids = model.generate(input_ids, max_new_tokens=4, temperature=0)
self.assertEqual(EXPECTED_OUTPUT_TOKEN_IDS, generated_ids[0][-2:].tolist())
# Assisted generation
assistant_model = model
assistant_model.generation_config.num_assistant_tokens = 2
assistant_model.generation_config.num_assistant_tokens_schedule = "constant"
generated_ids = model.generate(input_ids, max_new_tokens=4, temperature=0)
self.assertEqual(EXPECTED_OUTPUT_TOKEN_IDS, generated_ids[0][-2:].tolist())
del assistant_model
del model
backend_empty_cache(torch_device)
gc.collect()
@slow
@unittest.skip("not working with Ministral")
@pytest.mark.torch_export_test
def test_export_text_with_hybrid_cache(self):
# TODO: Exportability is not working
from transformers.testing_utils import is_torch_greater_or_equal
if not is_torch_greater_or_equal("2.6.0"):
self.skipTest(reason="This test requires torch >= 2.6 to run.")
from transformers.integrations.executorch import TorchExportableModuleForDecoderOnlyLM
model_id = "Mistralai/Ministral-8B-Instruct-2410"
model = MinistralForCausalLM.from_pretrained(
model_id,
generation_config=GenerationConfig(
use_cache=True,
cache_implementation="static",
cache_config={
"batch_size": 1,
"max_cache_len": 50,
},
),
)
# Export + HybridCache
model.eval()
exportable_module = TorchExportableModuleForDecoderOnlyLM(model)
exported_program = exportable_module.export(
input_ids=torch.tensor([[1]], dtype=torch.long, device=model.device),
cache_position=torch.tensor([0], dtype=torch.long, device=model.device),
)
logging.info(f"\nExported program: {exported_program}")
# Test generation with the exported model
prompt = "My favourite condiment is "
max_new_tokens_to_generate = 20
# Generate text with the exported model
tokenizer = AutoTokenizer.from_pretrained(model_id)
export_generated_text = TorchExportableModuleForDecoderOnlyLM.generate(
exported_program, tokenizer, prompt, max_new_tokens=max_new_tokens_to_generate
)
logging.info(f"\nExport generated texts: '{export_generated_text}'")
input_text = tokenizer(prompt, return_tensors="pt")
with torch.no_grad():
eager_outputs = model.generate(
**input_text,
max_new_tokens=max_new_tokens_to_generate,
do_sample=False, # Use greedy decoding to match the exported model
cache_implementation="static",
)
eager_generated_text = tokenizer.decode(eager_outputs[0], skip_special_tokens=True)
logging.info(f"\nEager generated texts: '{eager_generated_text}'")
self.assertEqual(export_generated_text, eager_generated_text)
@pytest.mark.flash_attn_test
@require_flash_attn
@slow
def test_past_sliding_window_generation(self):
try:
from datasets import load_dataset
except ImportError:
self.skipTest("datasets not found")
model = MinistralForCausalLM.from_pretrained(
"mistralai/Ministral-8B-Instruct-2410",
device_map="auto",
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
)
tokenizer = AutoTokenizer.from_pretrained("mistralai/Ministral-8B-Instruct-2410", legacy=False)
wiki = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
chunks = [x["text"] for x in wiki.select(range(550)) if x["text"].strip()]
real_corpus = "\n".join(chunks)
prompt = f"<s>[INST]{real_corpus} Question: Based on the text, at which depth of the continental shelf does H. Gammarus live?[/INST]"
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
input_length = inputs.input_ids.shape[1] # around 33k tokens > 32k sliding window
outputs = model.generate(**inputs, max_new_tokens=100, do_sample=False)
output_text = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
self.assertEqual(
output_text,
" H. Gammarus lives on the continental shelf at depths of 0 – 150 metres ( 0 – 492 ft ) , although not normally deeper than 50 m ( 160 ft ) .",
)
| MinistralIntegrationTest |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 314878,
"end": 319845
} | class ____:
def test_reduces_to_triang(self):
modes = [0, 0.3, 0.5, 1]
for mode in modes:
x = [0, mode, 1]
assert_almost_equal(stats.trapezoid.pdf(x, mode, mode),
stats.triang.pdf(x, mode))
assert_almost_equal(stats.trapezoid.cdf(x, mode, mode),
stats.triang.cdf(x, mode))
def test_reduces_to_uniform(self):
x = np.linspace(0, 1, 10)
assert_almost_equal(stats.trapezoid.pdf(x, 0, 1), stats.uniform.pdf(x))
assert_almost_equal(stats.trapezoid.cdf(x, 0, 1), stats.uniform.cdf(x))
def test_cases(self):
# edge cases
assert_almost_equal(stats.trapezoid.pdf(0, 0, 0), 2)
assert_almost_equal(stats.trapezoid.pdf(1, 1, 1), 2)
assert_almost_equal(stats.trapezoid.pdf(0.5, 0, 0.8),
1.11111111111111111)
assert_almost_equal(stats.trapezoid.pdf(0.5, 0.2, 1.0),
1.11111111111111111)
# straightforward case
assert_almost_equal(stats.trapezoid.pdf(0.1, 0.2, 0.8), 0.625)
assert_almost_equal(stats.trapezoid.pdf(0.5, 0.2, 0.8), 1.25)
assert_almost_equal(stats.trapezoid.pdf(0.9, 0.2, 0.8), 0.625)
assert_almost_equal(stats.trapezoid.cdf(0.1, 0.2, 0.8), 0.03125)
assert_almost_equal(stats.trapezoid.cdf(0.2, 0.2, 0.8), 0.125)
assert_almost_equal(stats.trapezoid.cdf(0.5, 0.2, 0.8), 0.5)
assert_almost_equal(stats.trapezoid.cdf(0.9, 0.2, 0.8), 0.96875)
assert_almost_equal(stats.trapezoid.cdf(1.0, 0.2, 0.8), 1.0)
def test_moments_and_entropy(self):
# issue #11795: improve precision of trapezoid stats
# Apply formulas from Wikipedia for the following parameters:
a, b, c, d = -3, -1, 2, 3 # => 1/3, 5/6, -3, 6
p1, p2, loc, scale = (b-a) / (d-a), (c-a) / (d-a), a, d-a
h = 2 / (d+c-b-a)
def moment(n):
return (h * ((d**(n+2) - c**(n+2)) / (d-c)
- (b**(n+2) - a**(n+2)) / (b-a)) /
(n+1) / (n+2))
mean = moment(1)
var = moment(2) - mean**2
entropy = 0.5 * (d-c+b-a) / (d+c-b-a) + np.log(0.5 * (d+c-b-a))
assert_almost_equal(stats.trapezoid.mean(p1, p2, loc, scale),
mean, decimal=13)
assert_almost_equal(stats.trapezoid.var(p1, p2, loc, scale),
var, decimal=13)
assert_almost_equal(stats.trapezoid.entropy(p1, p2, loc, scale),
entropy, decimal=13)
# Check boundary cases where scipy d=0 or d=1.
assert_almost_equal(stats.trapezoid.mean(0, 0, -3, 6), -1, decimal=13)
assert_almost_equal(stats.trapezoid.mean(0, 1, -3, 6), 0, decimal=13)
assert_almost_equal(stats.trapezoid.var(0, 1, -3, 6), 3, decimal=13)
def test_trapezoid_vect(self):
# test that array-valued shapes and arguments are handled
c = np.array([0.1, 0.2, 0.3])
d = np.array([0.5, 0.6])[:, None]
x = np.array([0.15, 0.25, 0.9])
v = stats.trapezoid.pdf(x, c, d)
cc, dd, xx = np.broadcast_arrays(c, d, x)
res = np.empty(xx.size, dtype=xx.dtype)
ind = np.arange(xx.size)
for i, x1, c1, d1 in zip(ind, xx.ravel(), cc.ravel(), dd.ravel()):
res[i] = stats.trapezoid.pdf(x1, c1, d1)
assert_allclose(v, res.reshape(v.shape), atol=1e-15)
# Check that the stats() method supports vector arguments.
v = np.asarray(stats.trapezoid.stats(c, d, moments="mvsk"))
cc, dd = np.broadcast_arrays(c, d)
res = np.empty((cc.size, 4)) # 4 stats returned per value
ind = np.arange(cc.size)
for i, c1, d1 in zip(ind, cc.ravel(), dd.ravel()):
res[i] = stats.trapezoid.stats(c1, d1, moments="mvsk")
assert_allclose(v, res.T.reshape(v.shape), atol=1e-15)
def test_trapezoid_fit_convergence_gh23503(self):
# gh-23503 reported that trapezoid.fit would consistently converge to a
# triangular distribution unless starting values were provided. Check that this
# is resolved.
# Generate test data from a trapezoidal distribution
rng = np.random.default_rng(23842359234598263956)
true_args = 0.3, 0.7, -1, 2
true_dist = stats.trapezoid(*true_args)
x = true_dist.rvs(1000, random_state=rng)
# fit to data
fitted_args = stats.trapezoid.fit(x)
# Should not converge to triangular distribution (c=d=1)
fitted_c, fitted_d = fitted_args[:2]
assert not np.allclose(fitted_c, 1, atol=0.1)
assert not np.allclose(fitted_d, 1, atol=0.1)
# objective function is better than with true values of parameters
true_llf = stats.trapezoid.nnlf(true_args, x)
fitted_llf = stats.trapezoid.nnlf(fitted_args, x)
assert fitted_llf < true_llf
| TestTrapezoid |
python | pandas-dev__pandas | pandas/tests/arithmetic/test_interval.py | {
"start": 1963,
"end": 10951
} | class ____:
@pytest.fixture(params=[operator.eq, operator.ne])
def op(self, request):
return request.param
@pytest.fixture(
params=[
IntervalArray.from_arrays,
IntervalIndex.from_arrays,
create_categorical_intervals,
create_series_intervals,
create_series_categorical_intervals,
],
ids=[
"IntervalArray",
"IntervalIndex",
"Categorical[Interval]",
"Series[Interval]",
"Series[Categorical[Interval]]",
],
)
def interval_constructor(self, request):
"""
Fixture for all pandas native interval constructors.
To be used as the LHS of IntervalArray comparisons.
"""
return request.param
def elementwise_comparison(self, op, interval_array, other):
"""
Helper that performs elementwise comparisons between `array` and `other`
"""
other = other if is_list_like(other) else [other] * len(interval_array)
expected = np.array([op(x, y) for x, y in zip(interval_array, other)])
if isinstance(other, Series):
return Series(expected, index=other.index)
return expected
def test_compare_scalar_interval(self, op, interval_array):
# matches first interval
other = interval_array[0]
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_numpy_array_equal(result, expected)
# matches on a single endpoint but not both
other = Interval(interval_array.left[0], interval_array.right[1])
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_numpy_array_equal(result, expected)
def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed):
interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
other = Interval(0, 1, closed=other_closed)
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_numpy_array_equal(result, expected)
def test_compare_scalar_na(self, op, interval_array, nulls_fixture, box_with_array):
box = box_with_array
obj = tm.box_expected(interval_array, box)
result = op(obj, nulls_fixture)
if nulls_fixture is pd.NA:
# GH#31882
exp = np.ones(interval_array.shape, dtype=bool)
expected = BooleanArray(exp, exp)
else:
expected = self.elementwise_comparison(op, interval_array, nulls_fixture)
if not (box is Index and nulls_fixture is pd.NA):
# don't cast expected from BooleanArray to ndarray[object]
xbox = get_upcast_box(obj, nulls_fixture, True)
expected = tm.box_expected(expected, xbox)
tm.assert_equal(result, expected)
rev = op(nulls_fixture, obj)
tm.assert_equal(rev, expected)
@pytest.mark.parametrize(
"other",
[
0,
1.0,
True,
"foo",
Timestamp("2017-01-01"),
Timestamp("2017-01-01", tz="US/Eastern"),
Timedelta("0 days"),
Period("2017-01-01", "D"),
],
)
def test_compare_scalar_other(self, op, interval_array, other):
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_numpy_array_equal(result, expected)
def test_compare_list_like_interval(self, op, interval_array, interval_constructor):
# same endpoints
other = interval_constructor(interval_array.left, interval_array.right)
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_equal(result, expected)
# different endpoints
other = interval_constructor(
interval_array.left[::-1], interval_array.right[::-1]
)
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_equal(result, expected)
# all nan endpoints
other = interval_constructor([np.nan] * 4, [np.nan] * 4)
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_equal(result, expected)
def test_compare_list_like_interval_mixed_closed(
self, op, interval_constructor, closed, other_closed
):
interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
other = interval_constructor(range(2), range(1, 3), closed=other_closed)
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"other",
[
(
Interval(0, 1),
Interval(Timedelta("1 day"), Timedelta("2 days")),
Interval(4, 5, "both"),
Interval(10, 20, "neither"),
),
(0, 1.5, Timestamp("20170103"), np.nan),
(
Timestamp("20170102", tz="US/Eastern"),
Timedelta("2 days"),
"baz",
pd.NaT,
),
],
)
def test_compare_list_like_object(self, op, interval_array, other):
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_numpy_array_equal(result, expected)
def test_compare_list_like_nan(self, op, interval_array, nulls_fixture):
other = [nulls_fixture] * 4
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"other",
[
np.arange(4, dtype="int64"),
np.arange(4, dtype="float64"),
date_range("2017-01-01", periods=4),
date_range("2017-01-01", periods=4, tz="US/Eastern"),
timedelta_range("0 days", periods=4),
period_range("2017-01-01", periods=4, freq="D"),
Categorical(list("abab")),
Categorical(date_range("2017-01-01", periods=4)),
pd.array(list("abcd")),
pd.array(["foo", 3.14, None, object()], dtype=object),
],
ids=lambda x: str(x.dtype),
)
def test_compare_list_like_other(self, op, interval_array, other):
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("length", [1, 3, 5])
@pytest.mark.parametrize("other_constructor", [IntervalArray, list])
def test_compare_length_mismatch_errors(self, op, other_constructor, length):
interval_array = IntervalArray.from_arrays(range(4), range(1, 5))
other = other_constructor([Interval(0, 1)] * length)
with pytest.raises(ValueError, match="Lengths must match to compare"):
op(interval_array, other)
@pytest.mark.parametrize(
"constructor, expected_type, assert_func",
[
(IntervalIndex, np.array, tm.assert_numpy_array_equal),
(Series, Series, tm.assert_series_equal),
],
)
def test_index_series_compat(self, op, constructor, expected_type, assert_func):
# IntervalIndex/Series that rely on IntervalArray for comparisons
breaks = range(4)
index = constructor(IntervalIndex.from_breaks(breaks))
# scalar comparisons
other = index[0]
result = op(index, other)
expected = expected_type(self.elementwise_comparison(op, index, other))
assert_func(result, expected)
other = breaks[0]
result = op(index, other)
expected = expected_type(self.elementwise_comparison(op, index, other))
assert_func(result, expected)
# list-like comparisons
other = IntervalArray.from_breaks(breaks)
result = op(index, other)
expected = expected_type(self.elementwise_comparison(op, index, other))
assert_func(result, expected)
other = [index[0], breaks[0], "foo"]
result = op(index, other)
expected = expected_type(self.elementwise_comparison(op, index, other))
assert_func(result, expected)
@pytest.mark.parametrize("scalars", ["a", False, 1, 1.0, None])
def test_comparison_operations(self, scalars):
# GH #28981
expected = Series([False, False])
s = Series([Interval(0, 1), Interval(1, 2)], dtype="interval")
result = s == scalars
tm.assert_series_equal(result, expected)
| TestComparison |
python | apache__airflow | dev/airflow_mypy/plugin/outputs.py | {
"start": 1357,
"end": 3012
} | class ____(Plugin):
"""Plugin to convert XComArg to the runtime type.
This allows us to pass an *XComArg* to a downstream task, such as::
@task
def f(a: str) -> int:
return len(a)
f(op.output) # "op" is an operator instance.
f(g()) # "g" is a taskflow task.
where the *a* argument of ``f`` should accept a *str* at runtime, but can be
provided with an *XComArg* in the DAG.
In the long run, it is probably a good idea to make *XComArg* a generic that
carries information about the task's return type, and build the entire XCom
mechanism into the type checker. But Python's type system is still limiting
in this regard now, and (using the above example) we yet to have a good way
to convert ``f``'s argument list from ``[str]`` to ``[XComArg[str] | str]``.
Perhaps *ParamSpec* will be extended enough one day to accommodate this.
"""
@staticmethod
def _treat_as_any(context: AttributeContext | MethodContext) -> Type:
"""Pretend *XComArg* is actually *typing.Any*."""
return AnyType(TypeOfAny.special_form, line=context.context.line, column=context.context.column)
def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
if fullname not in OUTPUT_PROPERTIES:
return None
return self._treat_as_any
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
if fullname not in TASK_CALL_FUNCTIONS:
return None
return self._treat_as_any
def plugin(version: str):
return OperatorOutputPlugin
| OperatorOutputPlugin |
python | walkccc__LeetCode | solutions/3522. Calculate Score After Performing Instructions/3522.py | {
"start": 0,
"end": 371
} | class ____:
def calculateScore(self, instructions: list[str], values: list[int]) -> int:
n = len(instructions)
ans = 0
i = 0
seen = set()
while 0 <= i < n and i not in seen:
seen.add(i)
if instructions[i] == 'add':
ans += values[i]
i += 1
elif instructions[i] == 'jump':
i += values[i]
return ans
| Solution |
python | catalyst-team__catalyst | catalyst/callbacks/batch_overfit.py | {
"start": 252,
"end": 4147
} | class ____(Callback):
"""Callback to overfit loaders with specified number of batches.
By default we use ``1`` batch for loader.
Args:
kwargs: loader names and their number of batches to overfit.
For example, if you have ``train``, ``train_additional``,
``valid`` and ``valid_additional`` loaders and wan't to overfit
``train`` on first 1 batch,
``train_additional`` on first 2 batches,
``valid`` - on first 20% of batches
and ``valid_additional`` - on 50% batches:
.. code-block:: python
from catalyst.dl import SupervisedRunner, BatchOverfitCallback
runner = SupervisedRunner()
runner.train(
...
loaders={
"train": ...,
"train_additional": ...,
"valid": ...,
"valid_additional":...
}
...
callbacks=[
...
BatchOverfitCallback(
train_additional=2,
valid=0.2,
valid_additional=0.5
),
...
]
...
)
Minimal working example
.. code-block:: python
import torch
from torch.utils.data import DataLoader, TensorDataset
from catalyst import dl
# data
num_samples, num_features = int(1e4), int(1e1)
X, y = torch.rand(num_samples, num_features), torch.rand(num_samples)
dataset = TensorDataset(X, y)
loader = DataLoader(dataset, batch_size=32, num_workers=1)
loaders = {"train": loader, "valid": loader}
# model, criterion, optimizer, scheduler
model = torch.nn.Linear(num_features, 1)
criterion = torch.nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters())
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [3, 6])
# model training
runner = dl.SupervisedRunner()
runner.train(
model=model,
criterion=criterion,
optimizer=optimizer,
scheduler=scheduler,
loaders=loaders,
logdir="./logdir",
num_epochs=8,
verbose=True,
callbacks=[dl.BatchOverfitCallback(train=10, valid=0.5)]
)
"""
def __init__(self, **kwargs):
"""Init."""
super().__init__(order=CallbackOrder.internal)
self.loader_batches = {}
for loader, num_batches in kwargs.items():
if not isinstance(num_batches, (int, float)):
raise TypeError(
"Expected loader num_batches type is int/float "
f"but got {type(num_batches)}"
)
self.loader_batches[loader] = num_batches
def on_epoch_start(self, runner: "IRunner") -> None:
"""Wraps loaders for current epoch.
If number-of-batches for loader is not provided then the first batch
from loader will be used for overfitting.
Args:
runner: current runner
"""
epoch_loaders = OrderedDict()
for name, loader in runner.loaders.items():
num_batches = self.loader_batches.get(name, 1)
if isinstance(num_batches, float):
num_batches = int(len(loader) * num_batches)
epoch_loaders[name] = BatchLimitLoaderWrapper(
loader=loader, num_batches=num_batches
)
runner.loaders = epoch_loaders
def on_epoch_end(self, runner: "IRunner"):
"""Unwraps loaders for current epoch.
Args:
runner: current runner
"""
runner.loaders = {
key: value.origin if isinstance(value, BatchLimitLoaderWrapper) else value
for key, value in runner.loaders.items()
}
__all__ = ["BatchOverfitCallback"]
| BatchOverfitCallback |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 62318,
"end": 63036
} | class ____(gdb.Command):
'Display the current python frame and all the frames within its call stack (if any)'
def __init__(self):
gdb.Command.__init__ (self,
"py-bt",
gdb.COMMAND_STACK,
gdb.COMPLETE_NONE)
def invoke(self, args, from_tty):
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return
sys.stdout.write('Traceback (most recent call first):\n')
while frame:
if frame.is_python_frame():
frame.print_traceback()
frame = frame.older()
PyBacktrace()
| PyBacktrace |
python | huggingface__transformers | tests/models/emu3/test_modeling_emu3.py | {
"start": 4715,
"end": 9813
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=False,
vocab_size=99,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=2,
num_key_value_heads=2,
intermediate_size=37,
max_position_embeddings=512,
initializer_range=0.02,
pad_token_id=0,
bos_token_id=1,
eos_token_id=2,
image_token_id=3,
image_size=15,
codebook_size=20,
temporal_downsample_factor=1,
base_channels=32,
vq_channel_multiplier=[1, 2, 1],
image_seq_length=12,
vq_img_token_start_id=3,
):
self.parent = parent
self.batch_size = batch_size
self.is_training = is_training
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.intermediate_size = intermediate_size
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
self.pad_token_id = pad_token_id
self.bos_token_id = bos_token_id
self.eos_token_id = eos_token_id
self.image_token_id = image_token_id
self.image_size = image_size
self.codebook_size = codebook_size
self.temporal_downsample_factor = temporal_downsample_factor
self.vq_channel_multiplier = vq_channel_multiplier
self.vq_img_token_start_id = vq_img_token_start_id
self.base_channels = base_channels
self.seq_length = seq_length + image_seq_length
self.image_seq_length = image_seq_length
def prepare_config_and_inputs(self):
config = self.get_config()
input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size)
input_ids[input_ids == self.image_token_id] = self.pad_token_id
input_ids[:, : self.image_seq_length] = self.image_token_id
attention_mask = input_ids.ne(self.pad_token_id).to(torch_device)
pixel_values = floats_tensor(
[
self.batch_size,
3,
self.image_size,
self.image_size,
]
)
image_sizes = [[self.image_size, self.image_size]] * self.batch_size
image_sizes = torch.tensor(image_sizes, device=torch_device, dtype=torch.int64)
return config, input_ids, attention_mask, pixel_values, image_sizes
def get_config(self):
# create dummy vocab map for image2bpe mapping if it needs remapping
# we assume that vocab size is big enough to account for `codebook_size` amount of
# image tokens somewhere at the beginning of total vocab size
vocab_map = {i: chr(i) for i in range(self.vocab_size)}
start = self.vq_img_token_start_id
end = self.vq_img_token_start_id + self.codebook_size
for i in range(start, end):
# dummy str for each token, anything that fits pattern "<|visual token XXXXXX|>"
vocab_map[i] = f"<|visual token{i:06d}|>"
# add tokens that have to be in the vocab, we'll retrieve their ids later in modeling code
vocab_map[self.image_token_id] = "<image>"
vocab_map[self.image_token_id + 1] = "<|extra_200|>"
vocab_map = {v: k for k, v in vocab_map.items()}
text_config = Emu3TextConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
num_key_value_heads=self.num_key_value_heads,
intermediate_size=self.intermediate_size,
max_position_embeddings=self.max_position_embeddings,
initializer_range=self.initializer_range,
pad_token_id=self.pad_token_id,
bos_token_id=self.bos_token_id,
eos_token_id=self.eos_token_id,
)
vq_config = {
"codebook_size": self.codebook_size,
"temporal_downsample_factor": self.temporal_downsample_factor,
"base_channels": self.base_channels,
"channel_multiplier": self.vq_channel_multiplier,
"hidden_size": self.base_channels,
"attn_resolutions": [],
}
return Emu3Config(text_config=text_config, vq_config=vq_config, vocabulary_map=vocab_map)
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
(
config,
input_ids,
attention_mask,
pixel_values,
image_sizes,
) = config_and_inputs
inputs_dict = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"pixel_values": pixel_values,
"image_sizes": image_sizes,
}
return config, inputs_dict
@require_torch
| Emu3Vision2TextModelTester |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/dual_cmake_autotools/package.py | {
"start": 296,
"end": 927
} | class ____(AutotoolsPackage, CMakePackage):
"""Package with two build systems."""
homepage = "http://www.example.com"
url = "http://www.example.com/dual-cmake-autotools-1.0.tar.gz"
version("1.0")
build_system("autotools", "cmake", default="autotools")
variant(
"generator",
default="make",
values=("make", "ninja"),
description="the build system generator to use",
when="build_system=cmake",
)
with when("build_system=cmake"):
depends_on("cmake@3.5.1:", type="build")
depends_on("cmake@3.14.0:", type="build", when="@2.1.0:")
| DualCmakeAutotools |
python | kamyu104__LeetCode-Solutions | Python/maximize-expression-of-three-elements.py | {
"start": 36,
"end": 541
} | class ____(object):
def maximizeExpressionOfThree(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = max(xrange(len(nums)), key=lambda x: nums[x])
nums[i], nums[-1] = nums[-1], nums[i]
j = max(xrange(len(nums)-1), key=lambda x: nums[x])
nums[j], nums[-2] = nums[-2], nums[j]
k = min(xrange(len(nums)-2), key=lambda x: nums[x])
nums[k], nums[0] = nums[0], nums[k]
return nums[-1]+nums[-2]-nums[0]
| Solution |
python | joke2k__faker | faker/providers/lorem/es_ES/__init__.py | {
"start": 68,
"end": 18207
} | class ____(LoremProvider):
"""Implement lorem provider for ``es_ES`` locale.
Sources:
- https://corpus.rae.es/frec/1000_formas.TXT
"""
word_list = (
"de",
"la",
"que",
"el",
"en",
"y",
"a",
"los",
"se",
"del",
"las",
"un",
"por",
"con",
"no",
"una",
"su",
"para",
"es",
"al",
"lo",
"como",
"más",
"o",
"pero",
"sus",
"le",
"ha",
"me",
"si",
"sin",
"sobre",
"este",
"ya",
"entre",
"cuando",
"todo",
"esta",
"ser",
"son",
"dos",
"también",
"fue",
"había",
"era",
"muy",
"años",
"hasta",
"desde",
"está",
"mi",
"porque",
"qué",
"sólo",
"han",
"yo",
"hay",
"vez",
"puede",
"todos",
"así",
"nos",
"ni",
"parte",
"tiene",
"él",
"uno",
"donde",
"bien",
"tiempo",
"mismo",
"ese",
"ahora",
"cada",
"e",
"vida",
"otro",
"después",
"te",
"otros",
"aunque",
"esa",
"eso",
"hace",
"otra",
"gobierno",
"tan",
"durante",
"siempre",
"día",
"tanto",
"ella",
"tres",
"sí",
"dijo",
"sido",
"gran",
"país",
"según",
"menos",
"mundo",
"año",
"antes",
"estado",
"contra",
"sino",
"forma",
"caso",
"nada",
"hacer",
"general",
"estaba",
"poco",
"estos",
"presidente",
"mayor",
"ante",
"unos",
"les",
"algo",
"hacia",
"casa",
"ellos",
"ayer",
"hecho",
"primera",
"mucho",
"mientras",
"además",
"quien",
"momento",
"millones",
"esto",
"españa",
"hombre",
"están",
"pues",
"hoy",
"lugar",
"madrid",
"nacional",
"trabajo",
"otras",
"mejor",
"nuevo",
"decir",
"algunos",
"entonces",
"todas",
"días",
"debe",
"política",
"cómo",
"casi",
"toda",
"tal",
"luego",
"pasado",
"primer",
"medio",
"va",
"estas",
"sea",
"tenía",
"nunca",
"poder",
"aquí",
"ver",
"veces",
"embargo",
"partido",
"personas",
"grupo",
"cuenta",
"pueden",
"tienen",
"misma",
"nueva",
"cual",
"fueron",
"mujer",
"frente",
"josé",
"tras",
"cosas",
"fin",
"ciudad",
"he",
"social",
"manera",
"tener",
"sistema",
"será",
"historia",
"muchos",
"juan",
"tipo",
"cuatro",
"dentro",
"nuestro",
"punto",
"dice",
"ello",
"cualquier",
"noche",
"aún",
"agua",
"parece",
"haber",
"situación",
"fuera",
"bajo",
"grandes",
"nuestra",
"ejemplo",
"acuerdo",
"habían",
"usted",
"estados",
"hizo",
"nadie",
"países",
"horas",
"posible",
"tarde",
"ley",
"importante",
"guerra",
"desarrollo",
"proceso",
"realidad",
"sentido",
"lado",
"mí",
"tu",
"cambio",
"allí",
"mano",
"eran",
"estar",
"san",
"número",
"sociedad",
"unas",
"centro",
"padre",
"gente",
"final",
"relación",
"cuerpo",
"obra",
"incluso",
"través",
"último",
"madre",
"mis",
"modo",
"problemas",
"cinco",
"carlos",
"hombres",
"información",
"ojos",
"muerte",
"nombre",
"algunas",
"público",
"mujeres",
"siglo",
"todavía",
"meses",
"mañana",
"esos",
"nosotros",
"hora",
"muchas",
"pueblo",
"alguna",
"dar",
"problema",
"don",
"da",
"tú",
"derecho",
"verdad",
"maría",
"unidos",
"podría",
"sería",
"junto",
"cabeza",
"aquel",
"luis",
"cuanto",
"tierra",
"equipo",
"segundo",
"director",
"dicho",
"cierto",
"casos",
"manos",
"nivel",
"podía",
"familia",
"largo",
"partir",
"falta",
"llegar",
"propio",
"ministro",
"cosa",
"primero",
"seguridad",
"hemos",
"mal",
"trata",
"algún",
"tuvo",
"respecto",
"semana",
"varios",
"real",
"sé",
"voz",
"paso",
"señor",
"mil",
"quienes",
"proyecto",
"mercado",
"mayoría",
"luz",
"claro",
"iba",
"éste",
"pesetas",
"orden",
"español",
"buena",
"quiere",
"aquella",
"programa",
"palabras",
"internacional",
"van",
"esas",
"segunda",
"empresa",
"puesto",
"ahí",
"propia",
"m",
"libro",
"igual",
"político",
"persona",
"últimos",
"ellas",
"total",
"creo",
"tengo",
"dios",
"c",
"española",
"condiciones",
"méxico",
"fuerza",
"solo",
"único",
"acción",
"amor",
"policía",
"puerta",
"pesar",
"zona",
"sabe",
"calle",
"interior",
"tampoco",
"música",
"ningún",
"vista",
"campo",
"buen",
"hubiera",
"saber",
"obras",
"razón",
"ex",
"niños",
"presencia",
"tema",
"dinero",
"comisión",
"antonio",
"servicio",
"hijo",
"última",
"ciento",
"estoy",
"hablar",
"dio",
"minutos",
"producción",
"camino",
"seis",
"quién",
"fondo",
"dirección",
"papel",
"demás",
"barcelona",
"idea",
"especial",
"diferentes",
"dado",
"base",
"capital",
"ambos",
"europa",
"libertad",
"relaciones",
"espacio",
"medios",
"ir",
"actual",
"población",
"empresas",
"estudio",
"salud",
"servicios",
"haya",
"principio",
"siendo",
"cultura",
"anterior",
"alto",
"media",
"mediante",
"primeros",
"arte",
"paz",
"sector",
"imagen",
"medida",
"deben",
"datos",
"consejo",
"personal",
"interés",
"julio",
"grupos",
"miembros",
"ninguna",
"existe",
"cara",
"edad",
"etc",
"movimiento",
"visto",
"llegó",
"puntos",
"actividad",
"bueno",
"uso",
"niño",
"difícil",
"joven",
"futuro",
"aquellos",
"mes",
"pronto",
"soy",
"hacía",
"nuevos",
"nuestros",
"estaban",
"posibilidad",
"sigue",
"cerca",
"resultados",
"educación",
"atención",
"gonzález",
"capacidad",
"efecto",
"necesario",
"valor",
"aire",
"investigación",
"siguiente",
"figura",
"central",
"comunidad",
"necesidad",
"serie",
"organización",
"nuevas",
"calidad",
"economía",
"carácter",
"jefe",
"estamos",
"prensa",
"control",
"sociales",
"universidad",
"militar",
"cabo",
"diez",
"fuerzas",
"congreso",
"ésta",
"hijos",
"justicia",
"mundial",
"dólares",
"juego",
"económica",
"políticos",
"duda",
"recursos",
"pública",
"crisis",
"próximo",
"tenemos",
"decisión",
"varias",
"popular",
"tenido",
"apenas",
"época",
"banco",
"presente",
"menor",
"quiero",
"pasar",
"resultado",
"televisión",
"encuentra",
"gracias",
"ministerio",
"conjunto",
"defensa",
"alguien",
"queda",
"hacen",
"pasa",
"resto",
"causa",
"seguir",
"allá",
"palabra",
"voy",
"cuya",
"vamos",
"mar",
"estudios",
"derechos",
"importancia",
"cuales",
"contrario",
"manuel",
"garcía",
"fuerte",
"sol",
"jóvenes",
"apoyo",
"habría",
"civil",
"miguel",
"pedro",
"partidos",
"libre",
"fuentes",
"administración",
"común",
"dejar",
"cine",
"salir",
"comunicación",
"b",
"experiencia",
"demasiado",
"plan",
"respuesta",
"energía",
"izquierda",
"función",
"principal",
"superior",
"naturaleza",
"podemos",
"unión",
"especialmente",
"rey",
"domingo",
"favor",
"cantidad",
"elecciones",
"clase",
"productos",
"españoles",
"conocer",
"teatro",
"importantes",
"evitar",
"color",
"actividades",
"mesa",
"p",
"decía",
"cuyo",
"debido",
"alta",
"francisco",
"secretario",
"objeto",
"quizá",
"posición",
"parecía",
"natural",
"elementos",
"hubo",
"objetivo",
"formas",
"única",
"pueda",
"origen",
"blanco",
"mismos",
"lleva",
"económico",
"opinión",
"ayuda",
"oficial",
"silencio",
"buenos",
"pensar",
"república",
"dónde",
"sangre",
"encuentro",
"siquiera",
"autor",
"reunión",
"haciendo",
"suelo",
"muestra",
"viejo",
"encima",
"resulta",
"tomar",
"bastante",
"siete",
"lucha",
"pudo",
"amigos",
"línea",
"sur",
"pocos",
"medidas",
"norte",
"partes",
"iglesia",
"tratamiento",
"existencia",
"cargo",
"grande",
"américa",
"boca",
"plaza",
"pie",
"trabajadores",
"poner",
"existen",
"viene",
"permite",
"análisis",
"argentina",
"acto",
"hechos",
"tiempos",
"políticas",
"radio",
"puedo",
"crecimiento",
"francia",
"compañía",
"amigo",
"autoridades",
"realizar",
"acciones",
"padres",
"diario",
"ve",
"derecha",
"ambiente",
"i",
"habrá",
"precisamente",
"enfermedad",
"especie",
"ejército",
"santa",
"cambios",
"río",
"sabía",
"seguro",
"espera",
"momentos",
"viaje",
"quería",
"ocho",
"vivir",
"región",
"formación",
"escuela",
"cuarto",
"valores",
"quedó",
"participación",
"éxito",
"baja",
"artículo",
"principales",
"fernando",
"metros",
"marcha",
"régimen",
"consecuencia",
"conocimiento",
"corazón",
"campaña",
"estructura",
"efectos",
"finalmente",
"modelo",
"carta",
"construcción",
"médico",
"miedo",
"mayores",
"entrada",
"humanos",
"sean",
"actitud",
"deja",
"dejó",
"d",
"llevar",
"negro",
"texto",
"mitad",
"estuvo",
"alrededor",
"acerca",
"peso",
"humano",
"pequeño",
"fecha",
"serán",
"doctor",
"ideas",
"vino",
"materia",
"llega",
"carrera",
"cierta",
"sola",
"psoe",
"lejos",
"juez",
"características",
"riesgo",
"fácil",
"diferencia",
"cultural",
"libros",
"práctica",
"mayo",
"nuestras",
"programas",
"memoria",
"llegado",
"plazo",
"expresión",
"diciembre",
"mantener",
"enero",
"volver",
"cuadro",
"producto",
"produce",
"europea",
"conciencia",
"tenían",
"atrás",
"felipe",
"creación",
"chile",
"precio",
"película",
"puerto",
"fuego",
"cuestión",
"pasó",
"costa",
"supuesto",
"local",
"habla",
"aspectos",
"cuba",
"sala",
"cámara",
"vuelta",
"vía",
"mirada",
"mejores",
"informe",
"unidad",
"distintos",
"suerte",
"tales",
"mira",
"llamado",
"técnica",
"título",
"s",
"principios",
"octubre",
"volvió",
"período",
"g",
"encontrar",
"democracia",
"aumento",
"fútbol",
"prueba",
"consumo",
"pese",
"ocasiones",
"exterior",
"solución",
"u",
"hija",
"sueño",
"parís",
"capaz",
"ocasión",
"industria",
"adelante",
"salida",
"ciencia",
"asunto",
"asociación",
"puso",
"intereses",
"oro",
"podrá",
"pregunta",
"oposición",
"entrar",
"señora",
"señaló",
"santiago",
"dolor",
"zonas",
"comercio",
"operación",
"tribunal",
"instituciones",
"temas",
"militares",
"junio",
"marco",
"sectores",
"hacerlo",
"aspecto",
"razones",
"contenido",
"juicio",
"electoral",
"considera",
"tendrá",
"mucha",
"voluntad",
"dicen",
"recuerdo",
"socialista",
"área",
"aparece",
"vio",
"cama",
"aun",
"presenta",
"pp",
"revolución",
"busca",
"abril",
"rodríguez",
"fiscal",
"lópez",
"victoria",
"violencia",
"primeras",
"pequeña",
"armas",
"debía",
"ii",
"esfuerzo",
"humana",
"posibilidades",
"centros",
"profesional",
"asimismo",
"grado",
"has",
"toma",
"distintas",
"material",
"carne",
"llama",
"particular",
"jorge",
"trabajar",
"propuesta",
"muerto",
"precios",
"reforma",
"hermano",
"corte",
"comenzó",
"etapa",
"obstante",
"pone",
"diversos",
"visita",
"concepto",
"pacientes",
"semanas",
"tipos",
"solamente",
"deseo",
"sistemas",
"encuentran",
"siguientes",
"martín",
"suficiente",
"marzo",
"propios",
"jamás",
"dan",
"club",
"instituto",
"constitución",
"curso",
"lenguaje",
"estilo",
"rosa",
"imposible",
"pablo",
"buscar",
"peor",
"piel",
"arriba",
"generales",
"septiembre",
"blanca",
"r",
"aquellas",
"teoría",
"animales",
"hicieron",
"larga",
"perdido",
"imágenes",
"paciente",
"conseguir",
"máximo",
"noviembre",
"j",
"líder",
"hospital",
"diversas",
"rafael",
"vuelve",
"destino",
"torno",
"proyectos",
"flores",
"niveles",
"afirmó",
"explicó",
"n",
"somos",
"términos",
"premio",
)
parts_of_speech: Dict[str, tuple] = {}
| Provider |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py | {
"start": 29631,
"end": 30044
} | class ____(Wav2Vec2ForXVector):
def __init__(self, config):
super().__init__(config)
__all__ = [
"Wav2Vec2ConformerForAudioFrameClassification",
"Wav2Vec2ConformerForCTC",
"Wav2Vec2ConformerForPreTraining",
"Wav2Vec2ConformerForSequenceClassification",
"Wav2Vec2ConformerForXVector",
"Wav2Vec2ConformerModel",
"Wav2Vec2ConformerPreTrainedModel",
]
| Wav2Vec2ConformerForXVector |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.